CS1 Lecture 31 Apr. 3, 2019

Similar documents
SPANNING TREES. Lecture 21 CS2110 Spring 2016

10/31/18. About A6, Prelim 2. Spanning Trees, greedy algorithms. Facts about trees. Undirected trees

Spanning Trees, greedy algorithms. Lecture 20 CS2110 Fall 2018

Spanning Trees 4/19/17. Prelim 2, assignments. Undirected trees

Spanning Trees. Lecture 22 CS2110 Spring 2017

Greedy Algorithms. Previous Examples: Huffman coding, Minimum Spanning Tree Algorithms

Spanning Trees, greedy algorithms. Lecture 22 CS2110 Fall 2017

Spanning Trees. Lecture 20 CS2110 Spring 2015

11/22/2016. Chapter 9 Graph Algorithms. Introduction. Definitions. Definitions. Definitions. Definitions

Chapter 9 Graph Algorithms

Simple Graph. General Graph

Chapter 9 Graph Algorithms

Chapter 9 Graph Algorithms

Design and Analysis of Algorithms

Chapter 14. Graphs Pearson Addison-Wesley. All rights reserved 14 A-1

CS 311 Discrete Math for Computer Science Dr. William C. Bulko. Graphs

Homework Assignment #3 Graph

Chapter 14 Section 3 - Slide 1

Optimization II: Dynamic programming

CS 206 Introduction to Computer Science II

ECE608 - Chapter 16 answers

Copyright 2000, Kevin Wayne 1

Algorithms IV. Dynamic Programming. Guoqiang Li. School of Software, Shanghai Jiao Tong University

Lecture 3. Brute Force

GRAPHS, GRAPH MODELS, GRAPH TERMINOLOGY, AND SPECIAL TYPES OF GRAPHS

Introduction to Computer Science

LECTURE NOTES OF ALGORITHMS: DESIGN TECHNIQUES AND ANALYSIS

2. True or false: even though BFS and DFS have the same space complexity, they do not always have the same worst case asymptotic time complexity.

CSCE 350: Chin-Tser Huang. University of South Carolina

Coping with the Limitations of Algorithm Power Exact Solution Strategies Backtracking Backtracking : A Scenario

CS61BL. Lecture 5: Graphs Sorting

CSC 421: Algorithm Design & Analysis. Spring 2015

Lecture 10 Graph Algorithms

Tutorial 7: Advanced Algorithms. (e) Give an example in which fixed-parameter tractability is useful.

EECS 203 Lecture 20. More Graphs

Lecture 14: General Problem-Solving Methods

CSC Design and Analysis of Algorithms. Lecture 4 Brute Force, Exhaustive Search, Graph Traversal Algorithms. Brute-Force Approach

Some Graph Theory for Network Analysis. CS 249B: Science of Networks Week 01: Thursday, 01/31/08 Daniel Bilar Wellesley College Spring 2008

Search Algorithms. IE 496 Lecture 17

Junior Circle Meeting 3 Circuits and Paths. April 18, 2010

Graph Theory. Part of Texas Counties.

Sankalchand Patel College of Engineering - Visnagar Department of Computer Engineering and Information Technology. Assignment

CS70 - Lecture 6. Graphs: Coloring; Special Graphs. 1. Review of L5 2. Planar Five Color Theorem 3. Special Graphs:

Introduction To Graphs and Networks. Fall 2013 Carola Wenk

Combinatorial Optimization - Lecture 14 - TSP EPFL

CS 310 Advanced Data Structures and Algorithms

Backtracking and Branch-and-Bound

CMPSCI611: The SUBSET-SUM Problem Lecture 18

Dijkstra s algorithm for shortest paths when no edges have negative weight.

1 st Grade Mathematics Learning Targets By Unit

Discrete Mathematics for CS Spring 2008 David Wagner Note 13. An Introduction to Graphs

We have already seen the transportation problem and the assignment problem. Let us take the transportation problem, first.

Chapter 9. Greedy Technique. Copyright 2007 Pearson Addison-Wesley. All rights reserved.

CSE 373 Final Exam 3/14/06 Sample Solution

Informed Search CS457 David Kauchak Fall 2011

Introduction to Algorithms / Algorithms I Lecturer: Michael Dinitz Topic: Shortest Paths Date: 10/13/15

14 Graph Theory. Exercise Set 14-1

Classic Graph Theory Problems

Chapter 6. The Traveling-Salesman Problem. Section 1. Hamilton circuits and Hamilton paths.

CS 161 Fall 2015 Final Exam

Ideally your algorithms for both parts should run in linear time. You will receive partial credit for a polynomial-time algorithm.

CS1 Lecture 2 Jan. 16, 2019

Introduction to Optimization

PATH FINDING AND GRAPH TRAVERSAL

Basics of Graph Theory

Computer Science 385 Design and Analysis of Algorithms Siena College Spring Topic Notes: Dynamic Programming

Notes for Lecture 24

CSE 21 Spring 2016 Homework 5. Instructions

CPSC 320 Sample Solution, Playing with Graphs!

Exercises Optimal binary search trees root

Greedy Algorithms and Huffman Coding

Design and Analysis of Algorithms 演算法設計與分析. Lecture 7 April 15, 2015 洪國寶

Design and Analysis of Algorithms

An Early Problem in Graph Theory. Clicker Question 1. Konigsberg and the River Pregel

The ADT priority queue Orders its items by a priority value The first item removed is the one having the highest priority value

CS 106X, Lecture 23 Dijkstra and A* Search

CS1 Lecture 27 Mar. 26, 2018

CSE 373 NOVEMBER 20 TH TOPOLOGICAL SORT

Graphs. The ultimate data structure. graphs 1

Graph Algorithms (part 3 of CSC 282),

Graph Algorithms Introduction to Data Structures. Ananda Gunawardena 7/31/2011 1

UNIT 3. Greedy Method. Design and Analysis of Algorithms GENERAL METHOD

Ma/CS 6a Class 8: Eulerian Cycles

Some Extra Information on Graph Search

Algorithms Dr. Haim Levkowitz

Grade 7/8 Math Circles Graph Theory - Solutions October 13/14, 2015

Discrete Mathematics and Probability Theory Fall 2009 Satish Rao,David Tse Note 8

56:272 Integer Programming & Network Flows Final Exam -- December 16, 1997

CS161 - Final Exam Computer Science Department, Stanford University August 16, 2008

Design and Analysis of Algorithms

Lecture 13. Reading: Weiss, Ch. 9, Ch 8 CSE 100, UCSD: LEC 13. Page 1 of 29

Graph Algorithms (part 3 of CSC 282),

COMP3121/3821/9101/ s1 Assignment 1

Graph definitions. There are two kinds of graphs: directed graphs (sometimes called digraphs) and undirected graphs. An undirected graph

Lecture Summary CSC 263H. August 5, 2016

Understand graph terminology Implement graphs using

Section 08: Solutions

looking ahead to see the optimum

Introduction to Algorithms I

(Refer Slide Time: 06:01)

Transcription:

CS Lecture 3 Apr. 3, 209 HW6 due Fri. Q3: think carefully about overlaps draw pictures Think dimension by dimension three D problems if they don t overlap in x, they don t overlap» Express this in terms of center x s and half-widths if.. if.. ---------------- Q4 Ensure legal moves i.e. if user enters an illegal choice, print something appropriate and ask for a new choice. Computer gameplay can be random (but must be legal). You can use, for instance, random.randint( )and random.choice( ) to choose (non-zero) number of balls and (non-empty) heap. (also fine, of course, if you make yours smarter than random) Q5 is very very easy compared to Q3 and Q4

Last time Fished objects/classes/object-oriented programming class attributes, inheritance Today Optimization and graph algorithms

Optimization and graph problems Many computing tasks these days involve solving optimization problems finding the smallest, biggest, best, cheapest of something In general, optimization problems are expressed in terms of two components An objective function that is to be minimized/maximized (e.g. airfare, travel distance, travel time) A set of constraints that must be met (e.g. route must include these intermediate cities, departure must be after 8am, arrival must be before noon) Many optimization problems can be addressed as problems on graphs (the computer science kind, consisting of nodes/vertices and edges/connections, not the 2D x-y plots you have been using to visualize running time behavior.) HW 7 will focus on optimization and graphs. Before we get to graphs, a quick look at other optimization problems

A simple optimization problem Suppose you need to give someone n cents in change (given US coins penny, nickel, dime, quarter). How do you do it with the minimum number of coins? greedily give as many large value coins as possible first, then next largest size, etc. That is, first as many quarters as possible, then as many dimes, E.g. for 56 : 2 quarters, nickel, penny What if we replace nickel (5c) with 3 cent and 4 cent coins? Does same greedy approach work? for 56 greedy approach yields 25, 25, 4,, but 25, 25, 3, 3 is fewer coins! For US coins, the algorithm works. It is an example of a broad class of greedy algorithms if you take Algorithms (CS3330), you will likely study more about greedy algorithms.

Greedy algorithms Generally, a greedy algorithm is one that proceeds as follows: At each step, choose the locally / apparently / immediately best option (e.g. the one that seems like to make the most progress toward a solution) The idea (hope!) behind greedy algorithms is that by making many locally optimal choices we end up with overall optimal solution. But, as we saw, doesn t always succeed! Sometimes need to work harder. Greedy algorithm for Travelling Salesperson problem? No, does not always yield optimal solution Greedy algorithm for shortest driving route between two cities? (E.g. driving directions in Google maps). Yes, Dijkstra s algorithm. Greedy algorithms are very important and useful. But you need to think carefully about whether greedy approach indeed gives you an optimal solution (or, if not, a good enough one) for more, see http://en.wikipedia.org/wiki/greedy_algorithm

Source: http://toddwschneider.com/posts/traveling-salesman-with-simulated-annealing-r-andshiny/

Source: http://toddwschneider.com/posts/traveling-salesman-with-simulated-annealing-r-andshiny/ See also nice short video at:http://www.youtube.com/watch?v=sc5cx8dratu&list=plxh6ufue9gktm5-bbfmtp_-avaniuiq&index=3

Egyptian fractions 3/4 -> sum of (different) fractions all with as numerator E.g. 3 / 4 -> / 2 + / 4 Greedy algorithm? Try in sequence ½, /3, ¼, /5, Implementing this will be Q of HW7. Note: DO NOT use any division it does not work well!) Lots of info about this problem at: http://www.maths.surrey.ac.uk/hostedsites/r.knott/fractions/egyptian.html

If current fraction is n/d and current candidate to subtract is /c: How do we know if /c is less than n/d? How do we calculate (n/d) - (/c)? both without using division?

Another optimization problem Value Weight clock 75 0 painting 90 9 radio 20 4 vase 50 2 book 0 computer 200 20 Burglar with a knapsack in a home full of valuable items Objective function: fill knapsack with maximum value Constraint: knapsack can only hold 20 pounds Algorithm to solve this?

Burglar filling knapsack Value Weight Val/wt clock 75 0 7.5 painting 90 9 0 radio 20 4 5 vase 50 2 25 book 0 0 Constraint: Knapsack can hold up to 20lbs computer 200 20 0 Greedy approach says to pick best at each step. What rule could we use for best here? Highest value -> Lowest weight -> computer only -> $200 total book, vase, radio painting, -> $70 total Highest value/weight -> vase, clock, book, radio -> $255 total None of these criteria produce the optimal solution for this particular situation (best total is $275 via clock, painting, book). We could easily write an algorithm that always find the best by trying every subset of items. However, this solution is in very efficient for many knapsack-like problems. If have n items, how many subsets? 2^n, so exhaustive search potentially very slow At present, no known efficient algorithm for knapsack problems

Graphs and optimization problems based on graphs Many important real-world problems can be modeled as optimization problems on graphs A graph is: A set of nodes (vertices) A set of edges (arcs) representing connections between pairs of nodes There are several types of graphs: Directed. Edges are one way from source to destination) Undirected. Edges have no particular direction can travel either way, see each node from other, etc. Weighted. Edges have associated numbers called weights that can be used to represent cost, time, flow capacity, etc. See Ch. 2 of follow-up book to our text Think Complexity - http://greenteapress.com/complexity/html/thinkcomplexity003.html

Directed graph edges are one way from source to destination Can have two (one each way) between a pair of nodes Node can have edge to self Example relationships: course prerequisite hyperlink between web pages street between intersections Twitter follower Infection spread from-to 2 3 CS20 CS2230 CS2820 4 5 CS3330

Undirected graph Edges have no direction. Can travel either direction Can have only one edge between a pair of nodes* Node cannot have edge to self Example relationships: Facebook friend Bordering countries/states 2 3 Missouri 4 5 Illinois Nebraska Iowa *another kind of graph multigraph relaxes this rule South Dak Minnesota Wisconsin n

Weighted graphs Variant of both directed and undirected graphs in which each edge has an associate number called a weight or cost Edge weight provides additional information about the relationship between the nodes. Example relationships: Airfare between two cities Distance between two cities Flow capacity of oil/water pipeline between two points Network bandwidth between two ISP nodes SFO CID 23 5 $95 $396 00 2 3 ORD $724 4 2 5 $395 $496 JFK

Classic graph problems Determine if a graph has a cycle, a path that loops back to start points (e.g. 2-4-5-3-2) Find a path (non-branching) that traverses each (undirected) edge exactly once Leonhard Euler and the Bridges of Königsberg Not possible in graph on top right Find the shortest path between source s and destination Different algorithms for weighted/unweighted graphs Find longest path between source and destination Find a path that visits each vertex exactly once A, E, D, C, F, B, A in example on bottom right Path of minimum cost that visits each vertex once A, E, D, C, B, F, A (cost 5) in example Assign no more than n different colors to vertices under constraint that no pair of connected vertices has the same color A 000 2 3 B 5 4 3 6 4 5 F 4 C 2 Some of these are easy (have fast algorithms), others hard (no known efficient solution) E D

Representing graphs How can we represent general graph in Python? Need to keep track of nodes Need to keep track of edges Several ways to represent graphs have been developed List of nodes and list of edges Adjacency matrix Adjacency lists Dictionary of dictionaries Efficiency of algorithms that solve graph problems can vary greatly depending on how graph are representated a strong influence on choice is the fact that one of the most common things needed in graph algorithms is access to immediate neighbors of a node (nodes that are destinations of edges for which current node is source)

Adjacency matrix 2 3 4 5 2 4 False True True True False 2 True False False False False 3 5 3 True False False True False 4 True False True False False 5 False False False False False Appealingly simple to understand and implement Use, e.g. a list of lists containing True/False, 0/, or similar NOT the most common graph representation for most problems. Can you think of a reason why? Consider representing Facebook friends graph where each node is a FB user and an edge exists between two nodes whenever the two are FB friends. One billion nodes. Adjacency matrix B x B in size! Your computer doesn t have that much storage. But FB graph can be represented in computer! How? The B x B would be mostly False/0 most people don t have huge number of friends. Should be representable in closer to B * median number of friends. Other representations enable this huge memory savings.

Adjacency list Use a dictionary with Nodes as keys Values are lists of neighbor nodes 2 3 4 5 KEY 2 3 4 5 VALUE [2, 4, 3] [] [, 4] [3, ] [] Compared to adjacency matrix: + Much less space (when, as is common, most nodes have only a small relatively small number of neighbors). Facebook graph. People have hundreds of friends, not many milliions - Query of does edge (i,j) exist? not O(). Must search list associated with node i to see if j is there. Turns out this is not crucial in many graph algorithms. (could address this using dictionary of dictionaries but often not necessary)

Next time and Monday Adjacency list graph representation BFS, DFS, and the HW7 word ladder problem