CS 5114: Theory of Algorithms. Graph Algorithms. A Tree Proof. Graph Traversals. Clifford A. Shaffer. Spring 2014
|
|
- Diane Simmons
- 5 years ago
- Views:
Transcription
1 epartment of omputer Science Virginia Tech lacksburg, Virginia opyright c 04 by lifford. Shaffer : Theory of lgorithms Title page : Theory of lgorithms lifford. Shaffer Spring 04 lifford. Shaffer epartment of omputer Science Virginia Tech lacksburg, Virginia Students should be familiar with inductive proofs, recursion, data structures, and programming at the S4 level. Spring 04 opyright c 04 by lifford. Shaffer : Theory of lgorithms Spring 04 / 60 Graph lgorithms Graph lgorithms Graph lgorithms Graphs are useful for representing a variety of concepts: ata Structures Relationships amilies ommunication Networks Road Maps Graphs are useful for representing a variety of concepts: ata Structures Relationships amilies ommunication Networks Road Maps : Theory of lgorithms Spring 04 / 60 Tree Proof efinition: free tree is a connected, undirected graph that has no cycles. Theorem: If T is a free tree having n vertices, then T has exactly n edges. Proof: y induction on n. ase ase: n =. T consists of vertex and 0 edges. Inductive Hypothesis: The theorem is true for a tree having n vertices. Inductive Step: If T has n vertices, then T contains a vertex of degree. Remove that vertex and its incident edge to obtain T, a free tree with n vertices. y IH, T has n edges. Thus, T has n edges. graph G = (V, ) consists of a set of vertices V, and a set of edges, such that each edge in is a connection between a pair of vertices in V. irected vs. Undirected Labeled graph, weighted graph Labels for edges vs. weights for edges Multiple edges, loops ycle, ircuit, path, simple path, tours ipartite, acyclic, connected Rooted tree, unrooted tree, free tree Tree Proof Tree Proof efinition: free tree is a connected, undirected graph that has no cycles. Theorem: If T is a free tree having n vertices, then T has exactly n edges. Proof: y induction on n. ase ase: n =. T consists of vertex and 0 edges. Inductive Hypothesis: The theorem is true for a tree having n vertices. Inductive Step: If T has n vertices, then T contains a vertex of degree. Remove that vertex and its incident edge to obtain T, a free tree with n vertices. y IH, T has n edges. Thus, T has n edges. This is close to a satisfactory definition for free tree. There are several equivalent definitions for free trees, with similar proofs to relate them. Why do we know that some vertex has degree? ecause the definition says that the ree Tree has no cycles. : Theory of lgorithms Spring 04 / 60 Graph Traversals Graph Traversals Graph Traversals Various problems require a way to traverse a graph that is, visit each vertex and edge in a systematic way. Three common traversals: ulerian tours Traverse each edge exactly once epth-first search Keeps vertices on a stack readth-first search Keeps vertices on a queue Various problems require a way to traverse a graph that is, visit each vertex and edge in a systematic way. a vertex may be visited multiple times Three common traversals: ulerian tours Traverse each edge exactly once epth-first search Keeps vertices on a stack readth-first search Keeps vertices on a queue : Theory of lgorithms Spring 04 4 / 60
2 (a) (b) ulerian Tours ulerian Tours ulerian Tours circuit that contains every edge exactly once. xample: f e a c b d Tour: b a f c d e. f xample: e a c b d g No ulerian tour. How can you tell for sure? circuit that contains every edge exactly once. xample: f e a c b d Tour: b a f c d e. f xample: e a c b d g No ulerian tour. How can you tell for sure? Why no tour? ecause some vertices have odd degree. ll even nodes is a necessary condition. Is it sufficient? : Theory of lgorithms Spring 04 / 60 ulerian Tour Proof Theorem: connected, undirected graph with m edges that has no vertices of odd degree has an ulerian tour. Proof: y induction on m. ase ase: Inductive Hypothesis: Inductive Step: Start with an arbitrary vertex and follow a path until you return to the vertex. Remove this circuit. What remains are connected components G, G,..., G k each with nodes of even degree and < m edges. y IH, each connected component has an ulerian tour. ombine the tours to get a tour of the entire graph. ulerian Tour Proof ulerian Tour Proof Theorem: connected, undirected graph with m edges that has no vertices of odd degree has an ulerian tour. Proof: y induction on m. ase ase: Inductive Hypothesis: Inductive Step: Start with an arbitrary vertex and follow a path until you return to the vertex. Remove this circuit. What remains are connected components G, G,..., Gk each with nodes of even degree and < m edges. y IH, each connected component has an ulerian tour. ombine the tours to get a tour of the entire graph. ase case: 0 edges and vertex fits the theorem. IH: The theorem is true for < m edges. lways possible to find a circuit starting at any arbitrary vertex, since each vertex has even degree. : Theory of lgorithms Spring 04 6 / 60 epth irst Search epth irst Search epth irst Search void S(Graph G, int v) { // epth first search PreVisit(G, v); // Take appropriate action G.setMark(v, VISIT); for (dge w = each neighbor of v) if (G.getMark(G.v(w)) == UNVISIT) S(G, G.v(w)); PostVisit(G, v); // Take appropriate action Initial call: S(G, r) where r is the root of the S. ost: Θ( V + ). void S(Graph G, int v) { // epth first search PreVisit(G, v); // Take appropriate action G.setMark(v, VISIT); for (dge w = each neighbor of v) if (G.getMark(G.v(w)) == UNVISIT) S(G, G.v(w)); PostVisit(G, v); // Take appropriate action Initial call: S(G, r) where r is the root of the S. ost: Θ( V + ). : Theory of lgorithms Spring 04 7 / 60 epth irst Search xample epth irst Search xample epth irst Search xample The directions are imposed by the traversal. This is the epth irst Search Tree. (a) (b) : Theory of lgorithms Spring 04 8 / 60
3 S Tree If we number the vertices in the order that they are marked, we get S numbers. Lemma 7.: very edge e is either in the S tree T, or connects two vertices of G, one of which is an ancestor of the other in T. S Tree Results: No cross edges. That is, no edges connecting vertices sideways in the tree. S Tree If we number the vertices in the order that they are marked, we get S numbers. Lemma 7.: very edge e is either in the S tree T, or connects two vertices of G, one of which is an ancestor of the other in T. Proof: onsider the first time an edge (v, w) is examined, with v the current vertex. If w is unmarked, then (v, w) is in T. If w is marked, then w has a smaller S number than v N (v, w) is an unexamined edge of w. Thus, w is still on the stack. That is, w is on a path from v. Proof: onsider the first time an edge (v, w) is examined, with v the current vertex. If w is unmarked, then (v, w) is in T. If w is marked, then w has a smaller S number than v N (v, w) is an unexamined edge of w. Thus, w is still on the stack. That is, w is on a path from v. : Theory of lgorithms Spring 04 9 / 60 S for irected Graphs S for irected Graphs S for irected Graphs Main problem: connected graph may not give a single S tree orward edges: (, ) ack edges: (, ) 9 8 ross edges: (6, ), (8, 7), (9, ), (9, 8), (4, ) Solution: Maintain a list of unmarked vertices. Whenever one S tree is complete, choose an arbitrary unmarked vertex as the root for a new tree. Main problem: connected graph may not give a single S tree orward edges: (, ) ack edges: (, ) 9 8 ross edges: (6, ), (8, 7), (9, ), (9, 8), (4, ) Solution: Maintain a list of unmarked vertices. Whenever one S tree is complete, choose an arbitrary unmarked vertex as the root for a new tree. : Theory of lgorithms Spring 04 0 / 60 irected ycles Lemma 7.4: Let G be a directed graph. G has a directed cycle iff every S of G produces a back edge. irected ycles See earlier lemma. irected ycles Lemma 7.4: Let G be a directed graph. G has a directed cycle iff every S of G produces a back edge. Proof: Suppose a S produces a back edge (v, w). v and w are in the same S tree, w an ancestor of v. (v, w) and the path in the tree from w to v form a directed cycle. Suppose G has a directed cycle. o a S on G. Let w be the vertex of with smallest S number. Let (v, w) be the edge of coming into w. v is a descendant of w in a S tree. Therefore, (v, w) is a back edge. Proof: Suppose a S produces a back edge (v, w). v and w are in the same S tree, w an ancestor of v. (v, w) and the path in the tree from w to v form a directed cycle. Suppose G has a directed cycle. o a S on G. Let w be the vertex of with smallest S number. Let (v, w) be the edge of coming into w. v is a descendant of w in a S tree. Therefore, (v, w) is a back edge. : Theory of lgorithms Spring 04 / 60 readth irst Search readth irst Search readth irst Search Like S, but replace stack with a queue. Visit vertex s neighbors before going deeper in tree. Like S, but replace stack with a queue. Visit vertex s neighbors before going deeper in tree. : Theory of lgorithms Spring 04 / 60
4 J (a) J J J6 J4 J (b) J7 readth irst Search lgorithm void S(Graph G, int start) { Queue Q(G.n()); Q.enqueue(start); G.setMark(start, VISIT); while (!Q.ismpty()) { int v = Q.dequeue(); PreVisit(G, v); // Take appropriate action for (dge w = each neighbor of v) if (G.getMark(G.v(w)) == UNVISIT) { G.setMark(G.v(w), VISIT); Q.enqueue(G.v(w)); PostVisit(G, v); // Take appropriate action readth irst Search lgorithm readth irst Search lgorithm void S(Graph G, int start) { Queue Q(G.n()); Q.enqueue(start); G.setMark(start, VISIT); while (!Q.ismpty()) { int v = Q.dequeue(); PreVisit(G, v); // Take appropriate action for (dge w = each neighbor of v) if (G.getMark(G.v(w)) == UNVISIT) { G.setMark(G.v(w), VISIT); Q.enqueue(G.v(w)); PostVisit(G, v); // Take appropriate action : Theory of lgorithms Spring 04 / 60 readth irst Search xample readth irst Search xample readth irst Search xample Non-tree edges connect vertices at levels differing by 0 or. We know this because if an edge had connected to a deeper level, then that target node would have been placed on the queue when the edge was encountered. (a) (b) Non-tree edges connect vertices at levels differing by 0 or. : Theory of lgorithms Spring 04 4 / 60 Topological Sort Topological Sort Topological Sort Problem: Given a set of jobs, courses, etc. with prerequisite constraints, output the jobs in an order that does not violate any of the prerequisites. Problem: Given a set of jobs, courses, etc. with prerequisite constraints, output the jobs in an order that does not violate any of the prerequisites. J6 J J J J7 J J4 : Theory of lgorithms Spring 04 / 60 Topological Sort lgorithm void topsort(graph G) { // Top sort: recursive for (int i=0; i<g.n(); i++) // Initialize Mark G.setMark(i, UNVISIT); for (i=0; i<g.n(); i++) // Process vertices if (G.getMark(i) == UNVISIT) tophelp(g, i); // all helper void tophelp(graph G, int v) { // Helper function G.setMark(v, VISIT); for (dge w = each neighbor of v) if (G.getMark(G.v(w)) == UNVISIT) tophelp(g, G.v(w)); printout(v); // PostVisit for Vertex v Topological Sort lgorithm Prints in reverse order. Topological Sort lgorithm void topsort(graph G) { // Top sort: recursive for (int i=0; i<g.n(); i++) // Initialize Mark G.setMark(i, UNVISIT); for (i=0; i<g.n(); i++) // Process vertices if (G.getMark(i) == UNVISIT) tophelp(g, i); // all helper void tophelp(graph G, int v) { // Helper function G.setMark(v, VISIT); for (dge w = each neighbor of v) if (G.getMark(G.v(w)) == UNVISIT) tophelp(g, G.v(w)); printout(v); // PostVisit for Vertex v : Theory of lgorithms Spring 04 6 / 60
5 Queue-based Topological Sort void topsort(graph G) { // Top sort: Queue Queue Q(G.n()); int ount[g.n()]; for (int v=0; v<g.n(); v++) ount[v] = 0; for (v=0; v<g.n(); v++) // Process every edge for (dge w each neighbor of v) ount[g.v(w)]++; // dd to v s count for (v=0; v<g.n(); v++) // Initialize Queue if (ount[v] == 0) Q.enqueue(v); while (!Q.ismpty()) { // Process the vertices int v = Q.dequeue(); printout(v); // PreVisit for v for (dge w = each neighbor of v) { ount[g.v(w)]--; // One less prereq if (ount[g.v(w)]==0) Q.enqueue(G.v(w)); Queue-based Topological Sort Queue-based Topological Sort void topsort(graph G) { // Top sort: Queue Queue Q(G.n()); int ount[g.n()]; for (int v=0; v<g.n(); v++) ount[v] = 0; for (v=0; v<g.n(); v++) // Process every edge for (dge w each neighbor of v) ount[g.v(w)]++; // dd to v s count for (v=0; v<g.n(); v++) // Initialize Queue if (ount[v] == 0) Q.enqueue(v); while (!Q.ismpty()) { // Process the vertices int v = Q.dequeue(); printout(v); // PreVisit for v for (dge w = each neighbor of v) { ount[g.v(w)]--; // One less prereq if (ount[g.v(w)]==0) Q.enqueue(G.v(w)); : Theory of lgorithms Spring 04 7 / 60 Shortest Paths Problems Shortest Paths Problems Shortest Paths Problems Input: graph with weights or costs associated with each edge. Output: The list of edges forming the shortest path. Sample problems: ind the shortest path between two specified vertices. ind the shortest path from vertex S to all other vertices. ind the shortest path between all pairs of vertices. Input: graph with weights or costs associated with each edge. Our algorithms will actually calculate only distances. Output: The list of edges forming the shortest path. Sample problems: ind the shortest path between two specified vertices. ind the shortest path from vertex S to all other vertices. ind the shortest path between all pairs of vertices. Our algorithms will actually calculate only distances. : Theory of lgorithms Spring 04 8 / 60 Shortest Paths efinitions Shortest Paths efinitions Shortest Paths efinitions d(, ) is the shortest distance from vertex to. w(, ) is the weight of the edge connecting to. If there is no such edge, then w(, ) =. 0 0 d(, ) is the shortest distance from vertex to. w(, ) = 0; d(, ) = 0 (through ). w(, ) is the weight of the edge connecting to. If there is no such edge, then w(, ) =. 0 0 : Theory of lgorithms Spring 04 9 / 60 Single Source Shortest Paths Single Source Shortest Paths Single Source Shortest Paths Given start vertex s, find the shortest path from s to all other vertices. Try : Visit all vertices in some order, compute shortest paths for all vertices seen so far, then add the shortest path to next vertex x. Problem: Shortest path to a vertex already processed might go through x. Solution: Process vertices in order of distance from s. Given start vertex s, find the shortest path from s to all other vertices. Try : Visit all vertices in some order, compute shortest paths for all vertices seen so far, then add the shortest path to next vertex x. Problem: Shortest path to a vertex already processed might go through x. Solution: Process vertices in order of distance from s. : Theory of lgorithms Spring 04 0 / 60
6 0 0 ijkstra s lgorithm xample ijkstra s lgorithm xample ijkstra s lgorithm xample Initial 0 Process Process Process Process Process Initial 0 Process Process Process Process Process : Theory of lgorithms Spring 04 / 60 ijkstra s lgorithm: rray () void ijkstra(graph G, int s) { // Use array int [G.n()]; for (int i=0; i<g.n(); i++) // Initialize [i] = ININITY; [s] = 0; for (i=0; i<g.n(); i++) { // Process vertices int v = minvertex(g, ); if ([v] == ININITY) return; // Unreachable G.setMark(v, VISIT); for (dge w = each neighbor of v) if ([G.v(w)] > ([v] + G.weight(w))) [G.v(w)] = [v] + G.weight(w); ijkstra s lgorithm: rray () ijkstra s lgorithm: rray () void ijkstra(graph G, int s) { // Use array int [G.n()]; for (int i=0; i<g.n(); i++) // Initialize [i] = ININITY; [s] = 0; for (i=0; i<g.n(); i++) { // Process vertices int v = minvertex(g, ); if ([v] == ININITY) return; // Unreachable G.setMark(v, VISIT); for (dge w = each neighbor of v) if ([G.v(w)] > ([v] + G.weight(w))) [G.v(w)] = [v] + G.weight(w); : Theory of lgorithms Spring 04 / 60 ijkstra s lgorithm: rray () ijkstra s lgorithm: rray () ijkstra s lgorithm: rray () // Get mincost vertex int minvertex(graph G, int* ) { int v; // Initialize v to an unvisited vertex; for (int i=0; i<g.n(); i++) if (G.getMark(i) == UNVISIT) { v = i; break; for (i++; i<g.n(); i++) // ind smallest val if ((G.getMark(i)==UNVISIT) && ([i]<[v])) v = i; return v; // Get mincost vertex int minvertex(graph G, int* ) { int v; // Initialize v to an unvisited vertex; for (int i=0; i<g.n(); i++) if (G.getMark(i) == UNVISIT) { v = i; break; for (i++; i<g.n(); i++) // ind smallest val if ((G.getMark(i)==UNVISIT) && ([i]<[v])) v = i; return v; pproach : Scan the table on each pass for closest vertex. Total cost: Θ( V + ) = Θ( V ). pproach : Scan the table on each pass for closest vertex. Total cost: Θ( V + ) = Θ( V ). : Theory of lgorithms Spring 04 / 60 ijkstra s lgorithm: Priority Queue () class lem { public: int vertex, dist; ; int key(lem x) { return x.dist; void ijkstra(graph G, int s) { // priority queue int v; lem temp; int [G.n()]; lem [G.e()]; temp.dist = 0; temp.vertex = s; [0] = temp; heap H(,, G.e()); // reate the heap for (int i=0; i<g.n(); i++) [i] = ININITY; [s] = 0; for (i=0; i<g.n(); i++) { // Get distances do { temp = H.removemin(); v = temp.vertex; while (G.getMark(v) == VISIT); G.setMark(v, VISIT); if ([v] == ININITY) return; // Unreachable ijkstra s lgorithm: Priority Queue () ijkstra s lgorithm: Priority Queue () class lem { public: int vertex, dist; ; int key(lem x) { return x.dist; void ijkstra(graph G, int s) { // priority queue int v; lem temp; int [G.n()]; lem [G.e()]; temp.dist = 0; temp.vertex = s; [0] = temp; heap H(,, G.e()); // reate the heap for (int i=0; i<g.n(); i++) [i] = ININITY; [s] = 0; for (i=0; i<g.n(); i++) { // Get distances do { temp = H.removemin(); v = temp.vertex; while (G.getMark(v) == VISIT); G.setMark(v, VISIT); if ([v] == ININITY) return; // Unreachable : Theory of lgorithms Spring 04 4 / 60
7 ijkstra s lgorithm: Priority Queue () ijkstra s lgorithm: Priority Queue () ijkstra s lgorithm: Priority Queue () for (dge w = each neighbor of v) if ([G.v(w)] > ([v] + G.weight(w))) { [G.v(w)] = [v] + G.weight(w); temp.dist = [G.v(w)]; temp.vertex = G.v(w); H.insert(temp); // Insert new distance pproach : Store unprocessed vertices using a min-heap to implement a priority queue ordered by value. Must update priority queue for each edge. Total cost: Θ(( V + ) log V ). for (dge w = each neighbor of v) if ([G.v(w)] > ([v] + G.weight(w))) { [G.v(w)] = [v] + G.weight(w); temp.dist = [G.v(w)]; temp.vertex = G.v(w); H.insert(temp); // Insert new distance pproach : Store unprocessed vertices using a min-heap to implement a priority queue ordered by value. Must update priority queue for each edge. Total cost: Θ(( V + ) log V ). : Theory of lgorithms Spring 04 / 60 ll Pairs Shortest Paths or every vertex u, v V, calculate d(u, v). ould run ijkstra s lgorithm V times. etter is loyd s lgorithm. efine a k-path from u to v to be any path whose intermediate vertices all have indices less than k ll Pairs Shortest Paths Multiple runs of ijkstra s algorithm ost: V log V = V log V for dense graph. ll Pairs Shortest Paths or every vertex u, v V, calculate d(u, v). ould run ijkstra s lgorithm V times. etter is loyd s lgorithm. efine a k-path from u to v to be any path whose intermediate vertices all have indices less than k. The issue driving the concept of k paths is how to efficiently check all the paths without computing any path more than once. 0, is a 0-path.,0, is a -path. 0,, is a -path, but not a or path. verything is a 4 path. : Theory of lgorithms Spring 04 6 / 60 loyd s lgorithm loyd s lgorithm loyd s lgorithm void loyd(graph G) { // ll-pairs shortest paths int [G.n()][G.n()]; // Store distances for (int i=0; i<g.n(); i++) // Initialize for (int j=0; j<g.n(); j++) [i][j] = G.weight(i, j); for (int k=0; k<g.n(); k++) // ompute k paths for (int i=0; i<g.n(); i++) for (int j=0; j<g.n(); j++) if ([i][j] > ([i][k] + [k][j])) [i][j] = [i][k] + [k][j]; void loyd(graph G) { // ll-pairs shortest paths int [G.n()][G.n()]; // Store distances for (int i=0; i<g.n(); i++) // Initialize for (int j=0; j<g.n(); j++) [i][j] = G.weight(i, j); for (int k=0; k<g.n(); k++) // ompute k paths for (int i=0; i<g.n(); i++) for (int j=0; j<g.n(); j++) if ([i][j] > ([i][k] + [k][j])) [i][j] = [i][k] + [k][j]; : Theory of lgorithms Spring 04 7 / 60 Minimum ost Spanning Trees Minimum ost Spanning Trees Minimum ost Spanning Trees Minimum ost Spanning Tree (MST) Problem: Input: n undirected, connected graph G. Output: The subgraph of G that has minimum total cost as measured by summing the values for all of the edges in the subset, and keeps the vertices connected. Minimum ost Spanning Tree (MST) Problem: Input: n undirected, connected graph G. Output: The subgraph of G that has minimum total cost as measured by summing the values for all of the edges in the subset, and keeps the vertices connected : Theory of lgorithms Spring 04 8 / 60
8 Marked Vertices v i, i < j vu vp correct edge e ej Prim s edge Unmarked Vertices v, i >= j i vu vj Key Theorem for MST Let V, V be an arbitrary, non-trivial partition of V. Let (v, v ), v V, v V, be the cheapest edge between V and V. Then (v, v ) is in some MST of G. Proof: Let T be an arbitrary MST of G. If (v, v ) is in T, then we are done. Otherwise, adding (v, v ) to T creates a cycle. t least one edge (u, u ) of other than (v, v ) must be between V and V. c(u, u ) c(v, v ). Let T = T {(v, v ) {(u, u ). Then, T is a spanning tree of G and c(t ) c(t ). ut c(t ) is minimum cost. Therefore, c(t ) = c(t ) and T is a MST containing (v, v ). : Theory of lgorithms Spring 04 9 / 60 Key Theorem for MST Key Theorem for MST Let V, V be an arbitrary, non-trivial partition of V. Let (v, v), v V, v V, be the cheapest edge between V and V. Then (v, v) is in some MST of G. Proof: Let T be an arbitrary MST of G. If (v, v) is in T, then we are done. Otherwise, adding (v, v) to T creates a cycle. t least one edge (u, u) of other than (v, v) must be between V and V. c(u, u) c(v, v). Let T = T {(v, v) {(u, u). Then, T is a spanning tree of G and c(t ) c(t ). ut c(t ) is minimum cost. Therefore, c(t ) = c(t ) and T is a MST containing (v, v). There can only be multiple MSTs when there are edges with equal cost. Key Theorem igure Key Theorem igure Key Theorem igure Marked Vertices v i, i < j vu correct edge e Unmarked Vertices v, i >= j i vu vp ej Prim s edge vj : Theory of lgorithms Spring 04 0 / 60 Prim s MST lgorithm () void Prim(Graph G, int s) { // Prim s MST alg int [G.n()]; int V[G.n()]; // istances for (int i=0; i<g.n(); i++) // Initialize [i] = ININITY; [s] = 0; for (i=0; i<g.n(); i++) { // Process vertices int v = minvertex(g, ); G.setMark(v, VISIT); if (v!= s) dddgetomst(v[v], v); if ([v] == ININITY) return; //v unreachable for (dge w = each neighbor of v) if ([G.v(w)] > G.weight(w)) { [G.v(w)] = G.weight(w); // Update dist V[G.v(w)] = v; // who came from Prim s MST lgorithm () Prim s MST lgorithm () void Prim(Graph G, int s) { // Prim s MST alg int [G.n()]; int V[G.n()]; // istances for (int i=0; i<g.n(); i++) // Initialize [i] = ININITY; [s] = 0; for (i=0; i<g.n(); i++) { // Process vertices int v = minvertex(g, ); G.setMark(v, VISIT); if (v!= s) dddgetomst(v[v], v); if ([v] == ININITY) return; //v unreachable for (dge w = each neighbor of v) if ([G.v(w)] > G.weight(w)) { [G.v(w)] = G.weight(w); // Update dist V[G.v(w)] = v; // who came from : Theory of lgorithms Spring 04 / 60 Prim s MST lgorithm () Prim s MST lgorithm () Prim s MST lgorithm () int minvertex(graph G, int* ) { int v; // Initialize v to any unvisited vertex for (int i=0; i<g.n(); i++) if (G.getMark(i) == UNVISIT) { v = i; break; for (i=0; i<g.n(); i++) // ind smallest value if ((G.getMark(i)==UNVISIT) && ([i]<[v])) v = i; return v; This is an example of a greedy algorithm. int minvertex(graph G, int* ) { int v; // Initialize v to any unvisited vertex for (int i=0; i<g.n(); i++) if (G.getMark(i) == UNVISIT) { v = i; break; for (i=0; i<g.n(); i++) // ind smallest value if ((G.getMark(i)==UNVISIT) && ([i]<[v])) v = i; return v; This is an example of a greedy algorithm. : Theory of lgorithms Spring 04 / 60
9 lternative Prim s Implementation () lternative Prim s Implementation () lternative Prim s Implementation () Like ijkstra s algorithm, can implement with priority queue. void Prim(Graph G, int s) { int v; // The current vertex int [G.n()]; // istance array int V[G.n()]; // Who s closest lem temp; lem [G.e()]; // Heap array temp.distance = 0; temp.vertex = s; [0] = temp; // Initialize heap array heap H(,, G.e()); // reate the heap for (int i=0; i<g.n(); i++) [i] = ININITY; [s] = 0; Like ijkstra s algorithm, can implement with priority queue. void Prim(Graph G, int s) { int v; // The current vertex int [G.n()]; // istance array int V[G.n()]; // Who s closest lem temp; lem [G.e()]; // Heap array temp.distance = 0; temp.vertex = s; [0] = temp; // Initialize heap array heap H(,, G.e()); // reate the heap for (int i=0; i<g.n(); i++) [i] = ININITY; [s] = 0; : Theory of lgorithms Spring 04 / 60 lternative Prim s Implementation () for (i=0; i<g.n(); i++) { // Now build MST do { temp = H.removemin(); v = temp.vertex; while (G.getMark(v) == VISIT); G.setMark(v, VISIT); if (v!= s) dddgetomst(v[v], v); if ([v] == ININITY) return; // Unreachable for (dge w = each neighbor of v) if ([G.v(w)] > G.weight(w)) { // Update [G.v(w)] = G.weight(w); V[G.v(w)] = v; // Who came from temp.distance = [G.v(w)]; temp.vertex = G.v(w); H.insert(temp); // Insert dist in heap lternative Prim s Implementation () lternative Prim s Implementation () for (i=0; i<g.n(); i++) { // Now build MST do { temp = H.removemin(); v = temp.vertex; while (G.getMark(v) == VISIT); G.setMark(v, VISIT); if (v!= s) dddgetomst(v[v], v); if ([v] == ININITY) return; // Unreachable for (dge w = each neighbor of v) if ([G.v(w)] > G.weight(w)) { // Update [G.v(w)] = G.weight(w); V[G.v(w)] = v; // Who came from temp.distance = [G.v(w)]; temp.vertex = G.v(w); H.insert(temp); // Insert dist in heap : Theory of lgorithms Spring 04 4 / 60 Kruskal s MST lgorithm () Kruskal s MST lgorithm () Kruskal s MST lgorithm () Kruskel(Graph G) { // Kruskal s MST algorithm Gentree (G.n()); // quivalence class array lem [G.e()]; // rray of edges for min-heap int edgecnt = 0; for (int i=0; i<g.n(); i++) // Put edges into for (dge w = G.first(i); G.isdge(w); w = G.next(w)) { [edgecnt].weight = G.weight(w); [edgecnt++].edge = w; heap H(, edgecnt, edgecnt); // Heapify edges int nummst = G.n(); // Init w/ n equiv classes Kruskel(Graph G) { // Kruskal s MST algorithm Gentree (G.n()); // quivalence class array lem [G.e()]; // rray of edges for min-heap int edgecnt = 0; for (int i=0; i<g.n(); i++) // Put edges into for (dge w = G.first(i); G.isdge(w); w = G.next(w)) { [edgecnt].weight = G.weight(w); [edgecnt++].edge = w; heap H(, edgecnt, edgecnt); // Heapify edges int nummst = G.n(); // Init w/ n equiv classes : Theory of lgorithms Spring 04 / 60 Kruskal s MST lgorithm () Kruskal s MST lgorithm () Kruskal s MST lgorithm () for (i=0; nummst>; i++) { // ombine lem temp = H.removemin(); // Next cheap edge dge w = temp.edge; int v = G.v(w); int u = G.v(w); if (.differ(v, u)) { // If different.union(v, u); // ombine dddgetomst(g.v(w), G.v(w)); // dd nummst--; // Now one less MST for (i=0; nummst>; i++) { // ombine lem temp = H.removemin(); // Next cheap edge dge w = temp.edge; int v = G.v(w); int u = G.v(w); if (.differ(v, u)) { // If different.union(v, u); // ombine dddgetomst(g.v(w), G.v(w)); // dd nummst--; // Now one less MST How do we compute function MSTof(v)? Solution: UNION-IN algorithm (Section 4.). How do we compute function MSTof(v)? Solution: UNION-IN algorithm (Section 4.). : Theory of lgorithms Spring 04 6 / 60
10 Initial Step Process edge (, ) Step Process edge (, ) Step Process edge (, ) Kruskal s lgorithm xample Total cost: Θ( V + log ). Initial Step Process edge (, ) Kruskal s lgorithm xample Kruskal s lgorithm xample Total cost: Θ( V + log ). ost is dominated by the edge sort. lternative: Use a min heap, quit when only one set left. Kth-smallest implementation. Step Process edge (, ) Step Process edge (, ) : Theory of lgorithms Spring 04 7 / 60 Matching Suppose there are n workers that we want to work in teams of two. Only certain pairs of workers are willing to work together. Problem: orm as many compatible non-overlapping teams as possible. Model using G, an undirected graph. Join vertices if the workers will work together. matching is a set of edges in G with no vertex in more than one edge (the edges are independent). maximal matching has no free pairs of vertices that can extend the matching. maximum matching has the greatest possible number of edges. perfect matching includes every vertex. Matching Matching Suppose there are n workers that we want to work in teams of two. Only certain pairs of workers are willing to work together. Problem: orm as many compatible non-overlapping teams as possible. Model using G, an undirected graph. Join vertices if the workers will work together. matching is a set of edges in G with no vertex in more than one edge (the edges are independent). maximal matching has no free pairs of vertices that can extend the matching. maximum matching has the greatest possible number of edges. perfect matching includes every vertex. n example: (-) is a matching. (-) (, 4) is both maximal and maximum. Take away the edge (-4). Then (, ) would be maximal but not a maximum matching. 4 : Theory of lgorithms Spring 04 8 / 60 Very ense Graphs () Theorem: Let G = (V, ) be an undirected graph with V = n and every vertex having degree n. Then G contains a perfect matching. Proof: Suppose that G does not contain a perfect matching. Let M be a max matching. M < n. There must be two unmatched vertices v, v that are not adjacent. very vertex adjacent to v or to v is matched. Let M M be the set of edges involved in matching the neighbors of v and v. There are n edges from v and v to vertices covered by M, but M < n. Very ense Graphs () Very ense Graphs () Theorem: Let G = (V, ) be an undirected graph with V = n and every vertex having degree n. Then G contains a perfect matching. Proof: Suppose that G does not contain a perfect matching. Let M be a max matching. M < n. There must be two unmatched vertices v, v that are not adjacent. very vertex adjacent to v or to v is matched. Let M M be the set of edges involved in matching the neighbors of v and v. There are n edges from v and v to vertices covered by M, but M < n. There must be two unmatched vertices not adjacent: Otherwise it would either be perfect (if there are no free vertices) or we could just match v and v (because they are adjacent). very adjacent vertex is matched, otherwise the matching would not be maximal. See Manber igure.76. : Theory of lgorithms Spring 04 9 / 60 Very ense Graphs () Very ense Graphs () Very ense Graphs () Proof: (continued) Thus, some edge of M is adjacent to edges from v and v. Let (u, u) be such an edge. Replacing (u, u) with (v, u) and (v, u) results in a larger matching. Theorem proven by contradiction. Proof: (continued) Thus, some edge of M is adjacent to edges from v and v. Let (u, u ) be such an edge. Replacing (u, u ) with (v, u ) and (v, u ) results in a larger matching. Theorem proven by contradiction. Pigeonhole Principle : Theory of lgorithms Spring / 60
11 v v v u u u v u Generalizing the Insight Generalizing the Insight Generalizing the Insight v, u, u, v is a path from an unmatched vertex to an unmatched vertex such that alternate edges are unmatched and matched. In one step, switch unmatched and matched edges. Let G = (V, ) be an undirected graph and M a matching. n alternating path P goes from v to u, consists of v v v v alternately matched and unmatched edges, and both v and u are not in the match. u u u u v, u, u, v is a path from an unmatched vertex to an unmatched vertex such that alternate edges are unmatched and matched. In one step, switch unmatched and matched edges. Let G = (V, ) be an undirected graph and M a matching. n alternating path P goes from v to u, consists of alternately matched and unmatched edges, and both v and u are not in the match. : Theory of lgorithms Spring 04 4 / 60 Matching xample Matching xample Matching xample ,,, is NOT an alternating path (it does not start with an unmatch vertex). 7, 6,, 0, 9, 8 is an alternating path with respect to the given matching Observation: If a matching has an alternating path, then the size of the matching can be increased by one by switching matched and unmatched edges along the alternating path. 0 9 : Theory of lgorithms Spring 04 4 / 60 The lternating Path Theorem () Theorem: matching is maximum iff it has no alternating paths. Proof: learly, if a matching has alternating paths, then it is not maximum. Suppose M is a non-maximum matching. Let M be any maximum matching. Then, M > M. Let M M be the symmetric difference of M and M. M M = M M (M M ). G = (V, M M ) is a subgraph of G having maximum degree. The lternating Path Theorem () The lternating Path Theorem () Theorem: matching is maximum iff it has no alternating paths. Proof: learly, if a matching has alternating paths, then it is not maximum. Suppose M is a non-maximum matching. Let M be any maximum matching. Then, M > M. Let M M be the symmetric difference of M and M. M M = M M (M M ). G = (V, M M ) is a subgraph of G having maximum degree. The first point is the obvious part of the iff. If there is an alternating path, simply switch the match and umatched edges to augment the match. Symmetric difference: Those in either, but not both. The max degree is because a vertex matches one different vertex in M and M. : Theory of lgorithms Spring 04 4 / 60 The lternating Path Theorem () The lternating Path Theorem () The lternating Path Theorem () Proof: (continued) Therefore, the connected components of G are either even-length cycles or a path with alternating edges. Since M > M, there must be a component of G that is an alternating path having more M edges than M edges. Proof: (continued) Therefore, the connected components of G are either even-length cycles or a path with alternating edges. Since M > M, there must be a component of G that is an alternating path having more M edges than M edges. : Theory of lgorithms Spring / 60
12 ipartite Matching bipartite graph G = (U, V, ) consists of two disjoint sets of vertices U and V together with edges such that every edge has an endpoint in U and an endpoint in V. ipartite matching naturally models a number of assignment problems, such as assignment of workers to jobs. lternating paths will work to find a maximum bipartite matching. n alternating path always has one end in U and the other in V. If we direct unmatched edges from U to V and matched edges from V to U, then a directed path from an unmatched vertex in U to an unmatched vertex in V is an alternating path. : Theory of lgorithms Spring 04 4 / 60 ipartite Matching ipartite Matching bipartite graph G = (U, V, ) consists of two disjoint sets of vertices U and V together with edges such that every edge has an endpoint in U and an endpoint in V. ipartite matching naturally models a number of assignment problems, such as assignment of workers to jobs. lternating paths will work to find a maximum bipartite matching. n alternating path always has one end in U and the other in V. If we direct unmatched edges from U to V and matched edges from V to U, then a directed path from an unmatched vertex in U to an unmatched vertex in V is an alternating path. ipartite Matching xample ipartite Matching xample ipartite Matching xample, 8,, 0 is an alternating path. 4, 6,, 7, 4, 9 and, 8,, 0 are disjoint alternating paths that we can augment independently. Naive algorithm: ind a maximal matching (greedy algorithm). or each vertex: o a S or other search until an alternating path is found. Use the alternating path to improve the match , 8,, 0 is an alternating path. 0 V ( V + ), 6,, 7, 4, 9 and, 8,, 0 are disjoint alternating paths that we can augment independently. : Theory of lgorithms Spring / 60 lgorithm for Maximum ipartite Matching onstruct S subgraph from the set of unmatched vertices in U until a level with unmatched vertices in V is found. lgorithm for Maximum ipartite Matching lgorithm for Maximum ipartite Matching onstruct S subgraph from the set of unmatched vertices in U until a level with unmatched vertices in V is found. Greedily select a maximal set of disjoint alternating paths. ugment along each path independently. Repeat until no alternating paths remain. Time complexity O(( V + ) V ). Order doesn t matter. ind a path, remove its vertices, then repeat.ugment along the paths independently since they are disjoint. Greedily select a maximal set of disjoint alternating paths. ugment along each path independently. Repeat until no alternating paths remain. Time complexity O(( V + ) V ). : Theory of lgorithms Spring / 60
CS 5114: Theory of Algorithms. Graph Algorithms. A Tree Proof. Graph Traversals. Clifford A. Shaffer. Spring 2014
epartment of omputer Science Virginia Tech lacksburg, Virginia opyright c 04 by lifford. Shaffer : Theory of lgorithms Title page : Theory of lgorithms lifford. Shaffer Spring 04 lifford. Shaffer epartment
More information// Source code example for "A Practical Introduction to Data Structures and // Algorithm Analysis" by Clifford A. Shaffer, Prentice Hall, 1998.
// Source code example for "A Practical Introduction to Data Structures and // Algorithm Analysis" by Clifford A. Shaffer, Prentice Hall, 1998. // Copyright 1998 by Clifford A. Shaffer // graph.java interface
More informationECE4050 Data Structures and Algorithms. Lecture 8: Graphs
ECE4050 Data Structures and Algorithms Lecture 8: Graphs 1 Graphs A graph G = (V, E) consists of a set of vertices V, and a set of edges E, such that each edge in E is a connection between a pair of vertices
More informationData Structure Lecture#23: Graphs (Chapter 11) U Kang Seoul National University
Data Structure Lecture#23: Graphs (Chapter 11) U Kang Seoul National University U Kang 1 In This Lecture Basic terms and definitions of graphs How to represent graphs Graph traversal methods U Kang 2 Graphs
More information11.1 Terminology and Representations
Graphs Graphs provide the ultimate in data structure flexibility. Graphs can model both real-world systems and abstract problems, so they are used in hundreds of applications. Here is a small sampling
More informationTCOM 501: Networking Theory & Fundamentals. Lecture 11 April 16, 2003 Prof. Yannis A. Korilis
TOM 50: Networking Theory & undamentals Lecture pril 6, 2003 Prof. Yannis. Korilis 2 Topics Routing in ata Network Graph Representation of a Network Undirected Graphs Spanning Trees and Minimum Weight
More informationSpanning Tree. Lecture19: Graph III. Minimum Spanning Tree (MSP)
Spanning Tree (015) Lecture1: Graph III ohyung Han S, POSTH bhhan@postech.ac.kr efinition and property Subgraph that contains all vertices of the original graph and is a tree Often, a graph has many different
More informationData Structure Lecture#24: Graphs 2 (Chapter 11) U Kang Seoul National University
Data Structure Lecture#24: Graphs 2 (Chapter 11) U Kang Seoul National University U Kang 1 In This Lecture Shortest path problem Main idea of Dijkstra s algorithm Cost analysis of Dijkstra s algorithm
More informationSpanning Trees. CSE373: Data Structures & Algorithms Lecture 17: Minimum Spanning Trees. Motivation. Observations. Spanning tree via DFS
Spanning Trees S: ata Structures & lgorithms Lecture : Minimum Spanning Trees simple problem: iven a connected undirected graph =(V,), find a minimal subset of edges such that is still connected graph
More informationSingle Source, Shortest Path Problem
Lecture : From ijkstra to Prim Today s Topics: ijkstra s Shortest Path lgorithm epth First Search Spanning Trees Minimum Spanning Trees Prim s lgorithm overed in hapter 9 in the textbook Some slides based
More informationAnalysis of Algorithms Prof. Karen Daniels
UMass Lowell omputer Science 91.404 nalysis of lgorithms Prof. Karen aniels Spring, 2013 hapter 22: raph lgorithms & rief Introduction to Shortest Paths [Source: ormen et al. textbook except where noted]
More informationLecture 13: Weighted Shortest Paths. These slides include material originally prepared by Dr. Ron Cytron and Dr. Steve Cole.
Lecture : Weighted Shortest Paths These slides include material originally prepared by r. Ron ytron and r. Steve ole. nnouncements Lab code and post-lab due tonight Lab released tomorrow ijkstra s algorithm
More informationCAD Algorithms. Shortest Path
lgorithms Shortest Path lgorithms Mohammad Tehranipoor epartment September 00 Shortest Path Problem: ind the best way of getting from s to t where s and t are vertices in a graph. est: Min (sum of the
More informationMinimum Spanning Trees
Minimum Spanning Trees Overview Problem A town has a set of houses and a set of roads. A road connects and only houses. A road connecting houses u and v has a repair cost w(u, v). Goal: Repair enough (and
More informationMinimum-Spanning-Tree problem. Minimum Spanning Trees (Forests) Minimum-Spanning-Tree problem
Minimum Spanning Trees (Forests) Given an undirected graph G=(V,E) with each edge e having a weight w(e) : Find a subgraph T of G of minimum total weight s.t. every pair of vertices connected in G are
More informationUndirected graph is a special case of a directed graph, with symmetric edges
S-6S- ijkstra s lgorithm -: omputing iven a directed weighted graph (all weights non-negative) and two vertices x and y, find the least-cost path from x to y in. Undirected graph is a special case of a
More informationCISC 320 Introduction to Algorithms Fall Lecture 15 Depth First Search
IS 320 Introduction to lgorithms all 2014 Lecture 15 epth irst Search 1 Traversing raphs Systematic search of every edge and vertex of graph (directed or undirected) fficiency: each edge is visited no
More informationLecture 3: Graphs and flows
Chapter 3 Lecture 3: Graphs and flows Graphs: a useful combinatorial structure. Definitions: graph, directed and undirected graph, edge as ordered pair, path, cycle, connected graph, strongly connected
More informationMinimum Spanning Trees My T. UF
Introduction to Algorithms Minimum Spanning Trees @ UF Problem Find a low cost network connecting a set of locations Any pair of locations are connected There is no cycle Some applications: Communication
More informationWeek 9 Student Responsibilities. Mat Example: Minimal Spanning Tree. 3.3 Spanning Trees. Prim s Minimal Spanning Tree.
Week 9 Student Responsibilities Reading: hapter 3.3 3. (Tucker),..5 (Rosen) Mat 3770 Spring 01 Homework Due date Tucker Rosen 3/1 3..3 3/1 DS & S Worksheets 3/6 3.3.,.5 3/8 Heapify worksheet ttendance
More informationCS1800: Graph Algorithms (2nd Part) Professor Kevin Gold
S1800: raph lgorithms (2nd Part) Professor Kevin old Summary So ar readth-irst Search (S) and epth-irst Search (S) are two efficient algorithms for finding paths on graphs. S also finds the shortest path.
More informationOutline and Reading. Minimum Spanning Tree. Minimum Spanning Tree. Cycle Property. Minimum Spanning Trees ( 12.7)
Outline and Reading Minimum Spanning Tree PV 1 1 1 1 JK 1 15 SO 11 1 LX 15 Minimum Spanning Trees ( 1.) efinitions crucial fact Prim-Jarnik s lgorithm ( 1..) Kruskal s lgorithm ( 1..1) 111 // :1 PM Minimum
More information3.1 Basic Definitions and Applications
Graphs hapter hapter Graphs. Basic efinitions and Applications Graph. G = (V, ) n V = nodes. n = edges between pairs of nodes. n aptures pairwise relationship between objects: Undirected graph represents
More informationModule 5 Graph Algorithms
Module 5 Graph lgorithms Dr. Natarajan Meghanathan Professor of Computer Science Jackson State University Jackson, MS 97 E-mail: natarajan.meghanathan@jsums.edu 5. Graph Traversal lgorithms Depth First
More informationIntroduction to Graphs. common/notes/ppt/
Introduction to Graphs http://people.cs.clemson.edu/~pargas/courses/cs212/ common/notes/ppt/ Introduction Graphs are a generalization of trees Nodes or verticies Edges or arcs Two kinds of graphs irected
More informationAn Early Problem in Graph Theory. Clicker Question 1. Konigsberg and the River Pregel
raphs Topic " Hopefully, you've played around a bit with The Oracle of acon at Virginia and discovered how few steps are necessary to link just about anybody who has ever been in a movie to Kevin acon,
More informationGraph Algorithms. Chapter 22. CPTR 430 Algorithms Graph Algorithms 1
Graph Algorithms Chapter 22 CPTR 430 Algorithms Graph Algorithms Why Study Graph Algorithms? Mathematical graphs seem to be relatively specialized and abstract Why spend so much time and effort on algorithms
More informationNote. Out of town Thursday afternoon. Willing to meet before 1pm, me if you want to meet then so I know to be in my office
raphs and Trees Note Out of town Thursday afternoon Willing to meet before pm, email me if you want to meet then so I know to be in my office few extra remarks about recursion If you can write it recursively
More informationMinimum Spanning Trees and Shortest Paths
Minimum Spanning Trees and Shortest Paths Prim's algorithm ijkstra's algorithm November, 017 inda eeren / eoffrey Tien 1 Recall: S spanning tree Starting from vertex 16 9 1 6 10 13 4 3 17 5 11 7 16 13
More informationUndirected Graphs. DSA - lecture 6 - T.U.Cluj-Napoca - M. Joldos 1
Undirected Graphs Terminology. Free Trees. Representations. Minimum Spanning Trees (algorithms: Prim, Kruskal). Graph Traversals (dfs, bfs). Articulation points & Biconnected Components. Graph Matching
More informationCS 341: Algorithms. Douglas R. Stinson. David R. Cheriton School of Computer Science University of Waterloo. February 26, 2019
CS 341: Algorithms Douglas R. Stinson David R. Cheriton School of Computer Science University of Waterloo February 26, 2019 D.R. Stinson (SCS) CS 341 February 26, 2019 1 / 296 1 Course Information 2 Introduction
More informationCampus Tour. 1/18/2005 4:08 AM Campus Tour 1
ampus Tour //00 :0 M ampus Tour Outline and Reading Overview of the assignment Review djacency matrix structure (..) Kruskal s MST algorithm (..) Partition T and implementation (..) The decorator pattern
More informationUndirected graph is a special case of a directed graph, with symmetric edges
ijkstra s lgorithm 7-: omputing iven a directed weighted graph(all weights non-negative) and two verticesxand y, find the least-cost path fromxtoy in. Undirected graph is a special case of a directed graph,
More informationCHAPTER 14 GRAPH ALGORITHMS ORD SFO LAX DFW
SO OR HPTR 1 GRPH LGORITHMS LX W KNOWLGMNT: THS SLIS R PT ROM SLIS PROVI WITH T STRUTURS N LGORITHMS IN JV, GOORIH, TMSSI N GOLWSSR (WILY 16) 6 OS MINIMUM SPNNING TRS SO 16 PV OR 1 1 16 61 JK 1 1 11 WI
More informationGraph Applications. Topological Sort Shortest Path Problems Spanning Trees. Data Structures 1 Graph Applications
Graph Applications Topological Sort Shortest Path Problems Spanning Trees Data Structures 1 Graph Applications Application: Topological Sort Given a set of jobs, courses, etc. with prerequisite constraints,
More informationMinimum Spanning Trees Ch 23 Traversing graphs
Next: Graph Algorithms Graphs Ch 22 Graph representations adjacency list adjacency matrix Minimum Spanning Trees Ch 23 Traversing graphs Breadth-First Search Depth-First Search 11/30/17 CSE 3101 1 Graphs
More informationMinimum Spanning Trees and Shortest Paths
Minimum Spanning Trees and Shortest Paths Kruskal's lgorithm Prim's lgorithm Shortest Paths pril 04, 018 inda eeren / eoffrey Tien 1 Kruskal's algorithm ata types for implementation Kruskalslgorithm()
More informationL10 Graphs. Alice E. Fischer. April Alice E. Fischer L10 Graphs... 1/37 April / 37
L10 Graphs lice. Fischer pril 2016 lice. Fischer L10 Graphs... 1/37 pril 2016 1 / 37 Outline 1 Graphs efinition Graph pplications Graph Representations 2 Graph Implementation 3 Graph lgorithms Sorting
More informationAdvanced Data Structures and Algorithms
dvanced ata Structures and lgorithms ssociate Professor r. Raed Ibraheem amed University of uman evelopment, College of Science and Technology Computer Science epartment 2015 2016 epartment of Computer
More informationGraphs and Network Flows ISE 411. Lecture 7. Dr. Ted Ralphs
Graphs and Network Flows ISE 411 Lecture 7 Dr. Ted Ralphs ISE 411 Lecture 7 1 References for Today s Lecture Required reading Chapter 20 References AMO Chapter 13 CLRS Chapter 23 ISE 411 Lecture 7 2 Minimum
More informationMinimum Spanning Trees
Minimum Spanning Trees 0 OS SO LX PV OR 0 JK 0 WI 00 W MI 00 Goodrich, Tamassia Minimum Spanning Trees Minimum Spanning Trees Spanning subgraph Subgraph of a graph G containing all the vertices of G Spanning
More informationDecreasing a key FIB-HEAP-DECREASE-KEY(,, ) 3.. NIL. 2. error new key is greater than current key 6. CASCADING-CUT(, )
Decreasing a key FIB-HEAP-DECREASE-KEY(,, ) 1. if >. 2. error new key is greater than current key 3.. 4.. 5. if NIL and.
More informationUndirected Graphs. Hwansoo Han
Undirected Graphs Hwansoo Han Definitions Undirected graph (simply graph) G = (V, E) V : set of vertexes (vertices, nodes, points) E : set of edges (lines) An edge is an unordered pair Edge (v, w) = (w,
More informationCS 161 Lecture 11 BFS, Dijkstra s algorithm Jessica Su (some parts copied from CLRS) 1 Review
1 Review 1 Something I did not emphasize enough last time is that during the execution of depth-firstsearch, we construct depth-first-search trees. One graph may have multiple depth-firstsearch trees,
More informationCSC 1700 Analysis of Algorithms: Minimum Spanning Tree
CSC 1700 Analysis of Algorithms: Minimum Spanning Tree Professor Henry Carter Fall 2016 Recap Space-time tradeoffs allow for faster algorithms at the cost of space complexity overhead Dynamic programming
More informationKruskal s MST Algorithm
Kruskal s MST Algorithm CLRS Chapter 23, DPV Chapter 5 Version of November 5, 2014 Main Topics of This Lecture Kruskal s algorithm Another, but different, greedy MST algorithm Introduction to UNION-FIND
More informationCS200: Graphs. Rosen Ch , 9.6, Walls and Mirrors Ch. 14
CS200: Graphs Rosen Ch. 9.1-9.4, 9.6, 10.4-10.5 Walls and Mirrors Ch. 14 Trees as Graphs Tree: an undirected connected graph that has no cycles. A B C D E F G H I J K L M N O P Rooted Trees A rooted tree
More informationCopyright 2000, Kevin Wayne 1
Chapter 3 - Graphs Undirected Graphs Undirected graph. G = (V, E) V = nodes. E = edges between pairs of nodes. Captures pairwise relationship between objects. Graph size parameters: n = V, m = E. Directed
More information11/22/2016. Chapter 9 Graph Algorithms. Introduction. Definitions. Definitions. Definitions. Definitions
Introduction Chapter 9 Graph Algorithms graph theory useful in practice represent many real-life problems can be slow if not careful with data structures 2 Definitions an undirected graph G = (V, E) is
More informationChapter 9 Graph Algorithms
Chapter 9 Graph Algorithms 2 Introduction graph theory useful in practice represent many real-life problems can be slow if not careful with data structures 3 Definitions an undirected graph G = (V, E)
More informationUndirected Graphs. V = { 1, 2, 3, 4, 5, 6, 7, 8 } E = { 1-2, 1-3, 2-3, 2-4, 2-5, 3-5, 3-7, 3-8, 4-5, 5-6 } n = 8 m = 11
Chapter 3 - Graphs Undirected Graphs Undirected graph. G = (V, E) V = nodes. E = edges between pairs of nodes. Captures pairwise relationship between objects. Graph size parameters: n = V, m = E. V = {
More informationAdvanced Algorithms Class Notes for Monday, October 23, 2012 Min Ye, Mingfu Shao, and Bernard Moret
Advanced Algorithms Class Notes for Monday, October 23, 2012 Min Ye, Mingfu Shao, and Bernard Moret Greedy Algorithms (continued) The best known application where the greedy algorithm is optimal is surely
More informationCSC 8301 Design & Analysis of Algorithms: Kruskal s and Dijkstra s Algorithms
CSC 8301 Design & Analysis of Algorithms: Kruskal s and Dijkstra s Algorithms Professor Henry Carter Fall 2016 Recap Greedy algorithms iterate locally optimal choices to construct a globally optimal solution
More informationCS 6783 (Applied Algorithms) Lecture 5
CS 6783 (Applied Algorithms) Lecture 5 Antonina Kolokolova January 19, 2012 1 Minimum Spanning Trees An undirected graph G is a pair (V, E); V is a set (of vertices or nodes); E is a set of (undirected)
More informationLecture 6 Basic Graph Algorithms
CS 491 CAP Intro to Competitive Algorithmic Programming Lecture 6 Basic Graph Algorithms Uttam Thakore University of Illinois at Urbana-Champaign September 30, 2015 Updates ICPC Regionals teams will be
More informationAn Early Problem in Graph Theory
raphs Topic 2 " Hopefully, you've played around a bit with The Oracle of acon at Virginia and discovered how few steps are necessary to link just about anybody who has ever been in a movie to Kevin acon,
More informationMinimum spanning trees
Carlos Moreno cmoreno @ uwaterloo.ca EI-3 https://ece.uwaterloo.ca/~cmoreno/ece5 Standard reminder to set phones to silent/vibrate mode, please! During today's lesson: Introduce the notion of spanning
More informationCSE331 Introduction to Algorithms Lecture 15 Minimum Spanning Trees
CSE1 Introduction to Algorithms Lecture 1 Minimum Spanning Trees Antoine Vigneron antoine@unist.ac.kr Ulsan National Institute of Science and Technology July 11, 201 Antoine Vigneron (UNIST) CSE1 Lecture
More informationCampus Tour Goodrich, Tamassia. Campus Tour 1
ampus Tour 00 oodrich, Tamassia ampus Tour raph ssignment oals Learn and implement the adjacency matrix structure an Kruskal s minimum spanning tree algorithm Understand and use the decorator pattern and
More informationDFS on Directed Graphs BOS. Outline and Reading ( 6.4) Digraphs. Reachability ( 6.4.1) Directed Acyclic Graphs (DAG s) ( 6.4.4)
S on irected Graphs OS OR JK SO LX W MI irected Graphs S 1.3 1 Outline and Reading ( 6.4) Reachability ( 6.4.1) irected S Strong connectivity irected cyclic Graphs (G s) ( 6.4.4) Topological Sorting irected
More informationDijkstra s algorithm for shortest paths when no edges have negative weight.
Lecture 14 Graph Algorithms II 14.1 Overview In this lecture we begin with one more algorithm for the shortest path problem, Dijkstra s algorithm. We then will see how the basic approach of this algorithm
More informationCS 561, Lecture 9. Jared Saia University of New Mexico
CS 561, Lecture 9 Jared Saia University of New Mexico Today s Outline Minimum Spanning Trees Safe Edge Theorem Kruskal and Prim s algorithms Graph Representation 1 Graph Definition A graph is a pair of
More informationChapter 9. Greedy Technique. Copyright 2007 Pearson Addison-Wesley. All rights reserved.
Chapter 9 Greedy Technique Copyright 2007 Pearson Addison-Wesley. All rights reserved. Greedy Technique Constructs a solution to an optimization problem piece by piece through a sequence of choices that
More informationMatching Algorithms. Proof. If a bipartite graph has a perfect matching, then it is easy to see that the right hand side is a necessary condition.
18.433 Combinatorial Optimization Matching Algorithms September 9,14,16 Lecturer: Santosh Vempala Given a graph G = (V, E), a matching M is a set of edges with the property that no two of the edges have
More information22 Elementary Graph Algorithms. There are two standard ways to represent a
VI Graph Algorithms Elementary Graph Algorithms Minimum Spanning Trees Single-Source Shortest Paths All-Pairs Shortest Paths 22 Elementary Graph Algorithms There are two standard ways to represent a graph
More informationA region is each individual area or separate piece of the plane that is divided up by the network.
Math 135 Networks and graphs Key terms Vertex (Vertices) ach point of a graph dge n edge is a segment that connects two vertices. Region region is each individual area or separate piece of the plane that
More informationGraph ADT. Lecture18: Graph II. Adjacency Matrix. Representation of Graphs. Data Vertices and edges. Methods
Graph T S33: ata Structures (0) Lecture8: Graph II ohyung Han S, POSTH bhhan@postech.ac.kr ata Vertices and edges endvertices(e): an array of the two endvertices of e opposite(v,e): the vertex opposite
More information22 Elementary Graph Algorithms. There are two standard ways to represent a
VI Graph Algorithms Elementary Graph Algorithms Minimum Spanning Trees Single-Source Shortest Paths All-Pairs Shortest Paths 22 Elementary Graph Algorithms There are two standard ways to represent a graph
More informationTheory of Computing. Lecture 10 MAS 714 Hartmut Klauck
Theory of Computing Lecture 10 MAS 714 Hartmut Klauck Seven Bridges of Königsberg Can one take a walk that crosses each bridge exactly once? Seven Bridges of Königsberg Model as a graph Is there a path
More informationTheorem 2.9: nearest addition algorithm
There are severe limits on our ability to compute near-optimal tours It is NP-complete to decide whether a given undirected =(,)has a Hamiltonian cycle An approximation algorithm for the TSP can be used
More informationKonigsberg Bridge Problem
Graphs Konigsberg Bridge Problem c C d g A Kneiphof e D a B b f c A C d e g D a b f B Euler s Graph Degree of a vertex: the number of edges incident to it Euler showed that there is a walk starting at
More informationLecture 8: The Traveling Salesman Problem
Lecture 8: The Traveling Salesman Problem Let G = (V, E) be an undirected graph. A Hamiltonian cycle of G is a cycle that visits every vertex v V exactly once. Instead of Hamiltonian cycle, we sometimes
More informationDefinition: A graph G = (V, E) is called a tree if G is connected and acyclic. The following theorem captures many important facts about trees.
Tree 1. Trees and their Properties. Spanning trees 3. Minimum Spanning Trees 4. Applications of Minimum Spanning Trees 5. Minimum Spanning Tree Algorithms 1.1 Properties of Trees: Definition: A graph G
More informationCSE 332: Data Structures & Parallelism Lecture 22: Minimum Spanning Trees. Ruth Anderson Winter 2018
SE 33: Data Structures & Parallelism Lecture : Minimum Spanning Trees Ruth nderson Winter 08 Minimum Spanning Trees iven an undirected graph =(V,E), find a graph =(V, E ) such that: E is a subset of E
More informationMinimum Spanning Trees
Minimum Spanning Trees Problem A town has a set of houses and a set of roads. A road connects 2 and only 2 houses. A road connecting houses u and v has a repair cost w(u, v). Goal: Repair enough (and no
More informationCPS 102: Discrete Mathematics. Quiz 3 Date: Wednesday November 30, Instructor: Bruce Maggs NAME: Prob # Score. Total 60
CPS 102: Discrete Mathematics Instructor: Bruce Maggs Quiz 3 Date: Wednesday November 30, 2011 NAME: Prob # Score Max Score 1 10 2 10 3 10 4 10 5 10 6 10 Total 60 1 Problem 1 [10 points] Find a minimum-cost
More informationRouting. Effect of Routing in Flow Control. Relevant Graph Terms. Effect of Routing Path on Flow Control. Effect of Routing Path on Flow Control
Routing Third Topic of the course Read chapter of the text Read chapter of the reference Main functions of routing system Selection of routes between the origin/source-destination pairs nsure that the
More informationGraph Representations and Traversal
COMPSCI 330: Design and Analysis of Algorithms 02/08/2017-02/20/2017 Graph Representations and Traversal Lecturer: Debmalya Panigrahi Scribe: Tianqi Song, Fred Zhang, Tianyu Wang 1 Overview This lecture
More informationGreedy algorithms is another useful way for solving optimization problems.
Greedy Algorithms Greedy algorithms is another useful way for solving optimization problems. Optimization Problems For the given input, we are seeking solutions that must satisfy certain conditions. These
More informationGRAPH THEORY. What are graphs? Why graphs? Graphs are usually used to represent different elements that are somehow related to each other.
GRPH THEORY Hadrian ng, Kyle See, March 2017 What are graphs? graph G is a pair G = (V, E) where V is a nonempty set of vertices and E is a set of edges e such that e = {a, b where a and b are vertices.
More informationDesign and Analysis of Algorithms
CSE 101, Winter 018 D/Q Greed SP s DP LP, Flow B&B, Backtrack Metaheuristics P, NP Design and Analysis of Algorithms Lecture 8: Greed Class URL: http://vlsicad.ucsd.edu/courses/cse101-w18/ Optimization
More informationW4231: Analysis of Algorithms
W4231: Analysis of Algorithms 10/21/1999 Definitions for graphs Breadth First Search and Depth First Search Topological Sort. Graphs AgraphG is given by a set of vertices V and a set of edges E. Normally
More informationGraph Representation
Graph Representation Adjacency list representation of G = (V, E) An array of V lists, one for each vertex in V Each list Adj[u] contains all the vertices v such that there is an edge between u and v Adj[u]
More informationGreedy Algorithms. At each step in the algorithm, one of several choices can be made.
Greedy Algorithms At each step in the algorithm, one of several choices can be made. Greedy Strategy: make the choice that is the best at the moment. After making a choice, we are left with one subproblem
More informationECE 242 Data Structures and Algorithms. Graphs II. Lecture 27. Prof.
242 ata Structures and lgorithms http://www.ecs.umass.edu/~polizzi/teaching/242/ Graphs II Lecture 27 Prof. ric Polizzi Summary Previous Lecture omposed of vertices (nodes) and edges vertex or node edges
More informationOutline. Graphs. Divide and Conquer.
GRAPHS COMP 321 McGill University These slides are mainly compiled from the following resources. - Professor Jaehyun Park slides CS 97SI - Top-coder tutorials. - Programming Challenges books. Outline Graphs.
More informationAn iteration of Branch and Bound One iteration of Branch and Bound consists of the following four steps: Some definitions. Branch and Bound.
ranch and ound xamples and xtensions jesla@man.dtu.dk epartment of Management ngineering Technical University of enmark ounding ow do we get ourselves a bounding function? Relaxation. Leave out some constraints.
More informationMatching Theory. Figure 1: Is this graph bipartite?
Matching Theory 1 Introduction A matching M of a graph is a subset of E such that no two edges in M share a vertex; edges which have this property are called independent edges. A matching M is said to
More informationWeek 11: Minimum Spanning trees
Week 11: Minimum Spanning trees Agenda: Minimum Spanning Trees Prim s Algorithm Reading: Textbook : 61-7 1 Week 11: Minimum Spanning trees Minimum spanning tree (MST) problem: Input: edge-weighted (simple,
More informationCS521 \ Notes for the Final Exam
CS521 \ Notes for final exam 1 Ariel Stolerman Asymptotic Notations: CS521 \ Notes for the Final Exam Notation Definition Limit Big-O ( ) Small-o ( ) Big- ( ) Small- ( ) Big- ( ) Notes: ( ) ( ) ( ) ( )
More informationUC Berkeley CS 170: Efficient Algorithms and Intractable Problems Handout 8 Lecturer: David Wagner February 20, Notes 8 for CS 170
UC Berkeley CS 170: Efficient Algorithms and Intractable Problems Handout 8 Lecturer: David Wagner February 20, 2003 Notes 8 for CS 170 1 Minimum Spanning Trees A tree is an undirected graph that is connected
More informationIn this chapter, we consider some of the interesting problems for which the greedy technique works, but we start with few simple examples.
. Greedy Technique The greedy technique (also known as greedy strategy) is applicable to solving optimization problems; an optimization problem calls for finding a solution that achieves the optimal (minimum
More informationDEPTH-FIRST SEARCH A B C D E F G H I J K L M N O P. Graph Traversals. Depth-First Search
PTH-IRST SRH raph Traversals epth-irst Search H I J K L M N O P epth-irst Search 1 xploring a Labyrinth Without etting Lost depth-first search (S) in an undirected graph is like wandering in a labyrinth
More informationCS 561, Lecture 10. Jared Saia University of New Mexico
CS 561, Lecture 10 Jared Saia University of New Mexico Today s Outline The path that can be trodden is not the enduring and unchanging Path. The name that can be named is not the enduring and unchanging
More informationGraph Algorithms (part 3 of CSC 282),
Graph Algorithms (part of CSC 8), http://www.cs.rochester.edu/~stefanko/teaching/10cs8 1 Schedule Homework is due Thursday, Oct 1. The QUIZ will be on Tuesday, Oct. 6. List of algorithms covered in the
More informationApproximation Algorithms
Chapter 8 Approximation Algorithms Algorithm Theory WS 2016/17 Fabian Kuhn Approximation Algorithms Optimization appears everywhere in computer science We have seen many examples, e.g.: scheduling jobs
More informationAgenda. Graph Representation DFS BFS Dijkstra A* Search Bellman-Ford Floyd-Warshall Iterative? Non-iterative? MST Flow Edmond-Karp
Graph Charles Lin genda Graph Representation FS BFS ijkstra * Search Bellman-Ford Floyd-Warshall Iterative? Non-iterative? MST Flow Edmond-Karp Graph Representation djacency Matrix bool way[100][100];
More information2. CONNECTIVITY Connectivity
2. CONNECTIVITY 70 2. Connectivity 2.1. Connectivity. Definition 2.1.1. (1) A path in a graph G = (V, E) is a sequence of vertices v 0, v 1, v 2,..., v n such that {v i 1, v i } is an edge of G for i =
More informationCIS 121 Data Structures and Algorithms Minimum Spanning Trees
CIS 121 Data Structures and Algorithms Minimum Spanning Trees March 19, 2019 Introduction and Background Consider a very natural problem: we are given a set of locations V = {v 1, v 2,..., v n }. We want
More information6.1 Minimum Spanning Trees
CS124 Lecture 6 Fall 2018 6.1 Minimum Spanning Trees A tree is an undirected graph which is connected and acyclic. It is easy to show that if graph G(V,E) that satisfies any two of the following properties
More information