- A topological sort is an ordering of the vertices in a directed acyclic graph. The ordering is such that for every directed edge from vertex vi to vj, vi comes before vj in the ordering. A topological sort is not possible if the graph contains a cycle.
- The topological sort algorithm finds vertices with no incoming edges and adds them to the ordering. It then removes these vertices and repeats until the graph is empty or a cycle is detected.
- The example graph shows the in-degrees of vertices in a graph. Vertex A has an in-degree of 0 and would be first in the topological sort ordering.
1. The document discusses depth-first search (DFS), including its recursive implementation which eliminates the need for an explicit stack. 2. DFS classifies the edges of a graph as tree edges, back edges, forward edges, or cross edges. Tree edges and back edges are the only possible edge types in an undirected graph searched with DFS. 3. Applications of DFS include finding cycles, articulation vertices, topological sorting of directed acyclic graphs, and finding strongly connected components.
This document discusses several graph algorithms:
1) Topological sort is an ordering of the vertices of a directed acyclic graph (DAG) such that for every edge from vertex u to v, u comes before v in the ordering. It can be used to find a valid schedule respecting dependencies.
2) Strongly connected components are maximal subsets of vertices in a directed graph such that there is a path between every pair of vertices. An algorithm uses depth-first search to find SCCs in linear time.
3) Minimum spanning trees find a subset of edges that connects all vertices at minimum total cost. Prim's and Kruskal's algorithms find minimum spanning trees using greedy strategies in O(E
The document discusses using graphs to model real-world problems and algorithms for solving graph problems. It introduces basic graph terminology like vertices, edges, adjacency matrix/list representations. It then summarizes algorithms for finding shortest paths like Dijkstra's and Bellman-Ford. It also discusses using depth-first search to solve problems like detecting cycles, topological sorting of vertices, and calculating longest paths in directed acyclic graphs.
Prim's algorithm is used to find the minimum spanning tree of a connected, undirected graph. It works by continuously adding edges to a growing tree that connects vertices. The algorithm maintains two lists - a closed list of vertices already included in the minimum spanning tree, and a priority queue of open vertices. It starts with a single vertex in the closed list. Then it selects the lowest cost edge that connects an open vertex to a closed one, adds it to the tree and updates the lists. This process repeats until all vertices are in the closed list and connected by edges in the minimum spanning tree. The algorithm runs in O(E log V) time when using a binary heap priority queue.
Algorithm Design and Complexity - Course 8Traian Rebedea
The document discusses algorithms for finding strongly connected components (SCCs) in directed graphs. It describes Kosaraju's algorithm, which uses two depth-first searches (DFS) to find the SCCs. The first DFS computes a finishing time ordering, while the second DFS uses the transpose graph and the finishing time ordering to find the SCCs, outputting each SCC as a separate DFS tree. The algorithm runs in O(V+E) time and uses the property that the first DFS provides a topological sorting of the SCCs graph.
Single source stortest path bellman ford and dijkstraRoshan Tailor
This document discusses algorithms for finding shortest paths in weighted graphs:
- Dijkstra's algorithm finds single-source shortest paths in graphs with non-negative edge weights using a greedy approach and priority queue. It runs in O(ElogV) time with a Fibonacci heap.
- Bellman-Ford algorithm can handle graphs with negative edge weights by relaxing all edges V-1 times to detect negative cycles. It runs in O(VE) time.
- Examples are provided to illustrate the relaxation process and execution of both algorithms on sample graphs. Key properties like handling of negative weights and cycles are also explained.
This document discusses Bode plots, which are used to analyze the stability of linear time-invariant control systems. Bode plots graphically represent a system's transfer function and consist of a magnitude plot and a phase plot versus frequency. The magnitude plot shows the gain in decibels and the phase plot shows the phase angle. Together these plots can determine the gain and phase margins of a system, which indicate its stability. Examples are provided to demonstrate how to construct Bode plots from transfer functions and analyze system stability.
Topological sort is an algorithm that finds an ordering of tasks that respects their dependencies. It works by performing a depth-first search (DFS) on a directed graph where vertices represent tasks and edges represent dependencies. During DFS, each vertex is assigned a finishing time. The topological sort orders the tasks according to decreasing finishing time, so that all dependencies are satisfied. The algorithm runs in O(V+E) time, where V is the number of vertices and E is the number of edges.
a graph search algorithm that solves the single-source shortest path problem for a graph with non-negative edge path costs, producing a shortest path tree. This algorithm is often used in routing and as a subroutine in other graph algorithms.
The document discusses shortest path problems and algorithms for finding shortest paths in graphs. It describes Dijkstra's algorithm for finding the shortest path between two nodes in a graph with non-negative edge weights. Prim's algorithm is presented for finding a minimum spanning tree, which is a subgraph connecting all nodes with minimum total edge weight. An example graph is given and steps are outlined for applying Prim's algorithm to find its minimum spanning tree.
The Floyd-Warshall algorithm is used to find the shortest paths between all pairs of vertices in a weighted graph. It creates distance and sequence tables with rows and columns for each vertex. The distance table stores the weights of edges between vertices. The sequence table stores the path vertices to reach between each pair. It iterates through the tables, updating distances and paths at each iteration based on whether a new shortest path is found through a third vertex. When complete, the final distance table shows the shortest distance between each pair of vertices, and the sequence table shows the shortest path.
The Bellman–Ford algorithm is an algorithm that computes shortest paths from a single source vertex to all of the other vertices in a weighted digraph.
This document discusses topological sorting and strongly connected components in directed graphs. It defines topological sorting as a linear ordering of the vertices in a directed acyclic graph such that for every edge from vertex u to v, u comes before v in the ordering. It presents Kahn's algorithm for performing topological sorting in O(V+E) time. It also defines strongly connected components as maximal sets of vertices such that there is a path between every pair, and presents an algorithm to find the strongly connected components in a graph in O(V+E) time using depth-first search on the transpose graph.
This document describes Floyd's algorithm for solving the all-pairs shortest path problem in graphs. It begins with an introduction and problem statement. It then describes Dijkstra's algorithm as a greedy method for finding single-source shortest paths. It discusses graph representations and traversal methods. Finally, it provides pseudocode and analysis for Floyd's dynamic programming algorithm, which finds shortest paths between all pairs of vertices in O(n3) time.
This document describes the shortest path algorithm for finding the shortest distance between nodes in a weighted directed graph. It involves creating distance and sequence tables with N rows and N columns for a graph with N nodes. The algorithm iterates N-1 times to fill these tables. It works by checking if the distance between two nodes i and j can be made smaller by going through another node k, and updates the distance table with the minimum value at each step. The complexity of the algorithm is O(n2) space and O(n3) time for a graph with n nodes.
The document discusses different single-source shortest path algorithms. It begins by defining shortest path and different variants of shortest path problems. It then describes Dijkstra's algorithm and Bellman-Ford algorithm for solving the single-source shortest paths problem, even in graphs with negative edge weights. Dijkstra's algorithm uses relaxation and a priority queue to efficiently solve the problem in graphs with non-negative edge weights. Bellman-Ford can handle graphs with negative edge weights but requires multiple relaxation passes to converge. Pseudocode and examples are provided to illustrate the algorithms.
This document discusses bi-connected components in graphs. It defines an articulation point as a vertex in a connected graph whose removal would disconnect the graph. A bi-connected component is a maximal subgraph that contains no articulation points. The document presents algorithms for identifying articulation points and bi-connected components in a graph using depth-first search (DFS). It introduces the concepts of tree edges, back edges, forward edges and cross edges in a DFS tree and explains how to use these edge types to determine if a vertex is an articulation point based on the minimum discovery time of its descendant vertices.
The document discusses several shortest path algorithms for graphs, including Dijkstra's algorithm, Bellman-Ford algorithm, and Floyd-Warshall algorithm. Dijkstra's algorithm finds the shortest path from a single source node to all other nodes in a graph with non-negative edge weights. Bellman-Ford can handle graphs with negative edge weights but is slower. Floyd-Warshall can find shortest paths in a graph between all pairs of nodes.
The document describes the Floyd-Warshall algorithm for finding shortest paths in a weighted graph. It discusses the all-pairs shortest path problem, previous solutions using Dijkstra's algorithm and dynamic programming, and then presents the Floyd-Warshall algorithm as another dynamic programming solution. The algorithm works by computing the shortest path between all pairs of vertices where intermediate vertices are restricted to a given set. It does this using a bottom-up computation in O(V^3) time and O(V^2) space.
Part of Lecture Series on Automatic Control Systems delivered by me to Final year Diploma in Engg. Students. Equally useful for higher level. Easy language and step by step procedure for drawing Bode Plots. Three illustrative examples are included.
Dijkstra's algorithm finds the shortest paths from a source node to all other nodes in a graph. It works by maintaining two sets - one for nodes whose shortest paths are determined, and one for remaining nodes. It iteratively selects the node with the smallest distance from the source, calculates the distances to its neighbors, and moves them to the determined set until all nodes are processed. Some applications include finding fastest routes in transportation networks like road maps or flight schedules.
This document presents information about the shortest path problem in graphs. It defines key graph terms like vertices, edges, and discusses weighted, directed, and undirected graphs. It provides an example of finding the shortest path between two vertices in a graph using Dijkstra's algorithm and walks through the steps of running the algorithm on a sample graph to find the shortest path between vertices 1 and 9.
Dijkstra's algorithm is a link-state routing algorithm that computes the least-cost paths from one node to all other nodes in a network. It works by iteratively building a set N' of nodes whose least-cost paths are known, starting from a source node. In each iteration, it finds the node w not in N' with the minimum path cost and updates the cost estimates to nodes adjacent to w. This process repeats until all nodes are in N', providing the shortest path forwarding table for the source node. The algorithm runs in O(n^2) time for n nodes but more efficient implementations exist. Oscillations can potentially occur if link costs change based on traffic loads.
The document discusses the shortest path problem and Dijkstra's algorithm for solving it in graphs with non-negative edge weights. It defines the shortest path problem, explains that it is well-defined for non-negative graphs but not graphs with negative edge weights or cycles. It then describes Dijkstra's algorithm, how it works by iteratively finding the shortest path from the source to each vertex, and provides pseudocode for its implementation.
This document describes breadth-first search (BFS) graph algorithms. It begins by defining graphs and different graph representations. It then explains BFS, which explores a graph by exploring all of the neighbor nodes of the starting node, then all of the neighbors of the neighbors, and so on outwards in "waves" or breadth-first manner. The document provides pseudocode for BFS and walks through an example run on a sample graph to demonstrate how BFS works. It concludes by discussing the running time of BFS and providing an example programming assignment for implementing BFS.
1) The document discusses various linear transformations including reflection, rotation, and shear applied to geometric shapes like triangles and rectangles.
2) Reflection is illustrated for a triangle across the x-axis and y=-x line. Rotation is shown counterclockwise for different triangles around the origin.
3) Clockwise rotation and shear transformations in the x-direction are also demonstrated through examples using matrices applied to triangle and rectangle vertices. Plots of the transformed shapes are provided.
The document defines topological sorting as a linear ordering of the vertices in a directed acyclic graph (DAG) such that if there is a path from vertex vi to vk, then vi appears before vk in the ordering. It provides an algorithm for finding a topological sort by initializing an array, finding vertices of degree zero, adding them to the array, and removing outgoing edges. It also describes an algorithm for enumerating all possible topological sorts by computing indegree counts and pushing vertices with indegree of zero onto a stack.
Topological sort is an algorithm that finds an ordering of tasks that respects their dependencies. It works by performing a depth-first search (DFS) on a directed graph where vertices represent tasks and edges represent dependencies. During DFS, each vertex is assigned a finishing time. The topological sort orders the tasks according to decreasing finishing time, so that all dependencies are satisfied. The algorithm runs in O(V+E) time, where V is the number of vertices and E is the number of edges.
a graph search algorithm that solves the single-source shortest path problem for a graph with non-negative edge path costs, producing a shortest path tree. This algorithm is often used in routing and as a subroutine in other graph algorithms.
The document discusses shortest path problems and algorithms for finding shortest paths in graphs. It describes Dijkstra's algorithm for finding the shortest path between two nodes in a graph with non-negative edge weights. Prim's algorithm is presented for finding a minimum spanning tree, which is a subgraph connecting all nodes with minimum total edge weight. An example graph is given and steps are outlined for applying Prim's algorithm to find its minimum spanning tree.
The Floyd-Warshall algorithm is used to find the shortest paths between all pairs of vertices in a weighted graph. It creates distance and sequence tables with rows and columns for each vertex. The distance table stores the weights of edges between vertices. The sequence table stores the path vertices to reach between each pair. It iterates through the tables, updating distances and paths at each iteration based on whether a new shortest path is found through a third vertex. When complete, the final distance table shows the shortest distance between each pair of vertices, and the sequence table shows the shortest path.
The Bellman–Ford algorithm is an algorithm that computes shortest paths from a single source vertex to all of the other vertices in a weighted digraph.
This document discusses topological sorting and strongly connected components in directed graphs. It defines topological sorting as a linear ordering of the vertices in a directed acyclic graph such that for every edge from vertex u to v, u comes before v in the ordering. It presents Kahn's algorithm for performing topological sorting in O(V+E) time. It also defines strongly connected components as maximal sets of vertices such that there is a path between every pair, and presents an algorithm to find the strongly connected components in a graph in O(V+E) time using depth-first search on the transpose graph.
This document describes Floyd's algorithm for solving the all-pairs shortest path problem in graphs. It begins with an introduction and problem statement. It then describes Dijkstra's algorithm as a greedy method for finding single-source shortest paths. It discusses graph representations and traversal methods. Finally, it provides pseudocode and analysis for Floyd's dynamic programming algorithm, which finds shortest paths between all pairs of vertices in O(n3) time.
This document describes the shortest path algorithm for finding the shortest distance between nodes in a weighted directed graph. It involves creating distance and sequence tables with N rows and N columns for a graph with N nodes. The algorithm iterates N-1 times to fill these tables. It works by checking if the distance between two nodes i and j can be made smaller by going through another node k, and updates the distance table with the minimum value at each step. The complexity of the algorithm is O(n2) space and O(n3) time for a graph with n nodes.
The document discusses different single-source shortest path algorithms. It begins by defining shortest path and different variants of shortest path problems. It then describes Dijkstra's algorithm and Bellman-Ford algorithm for solving the single-source shortest paths problem, even in graphs with negative edge weights. Dijkstra's algorithm uses relaxation and a priority queue to efficiently solve the problem in graphs with non-negative edge weights. Bellman-Ford can handle graphs with negative edge weights but requires multiple relaxation passes to converge. Pseudocode and examples are provided to illustrate the algorithms.
This document discusses bi-connected components in graphs. It defines an articulation point as a vertex in a connected graph whose removal would disconnect the graph. A bi-connected component is a maximal subgraph that contains no articulation points. The document presents algorithms for identifying articulation points and bi-connected components in a graph using depth-first search (DFS). It introduces the concepts of tree edges, back edges, forward edges and cross edges in a DFS tree and explains how to use these edge types to determine if a vertex is an articulation point based on the minimum discovery time of its descendant vertices.
The document discusses several shortest path algorithms for graphs, including Dijkstra's algorithm, Bellman-Ford algorithm, and Floyd-Warshall algorithm. Dijkstra's algorithm finds the shortest path from a single source node to all other nodes in a graph with non-negative edge weights. Bellman-Ford can handle graphs with negative edge weights but is slower. Floyd-Warshall can find shortest paths in a graph between all pairs of nodes.
The document describes the Floyd-Warshall algorithm for finding shortest paths in a weighted graph. It discusses the all-pairs shortest path problem, previous solutions using Dijkstra's algorithm and dynamic programming, and then presents the Floyd-Warshall algorithm as another dynamic programming solution. The algorithm works by computing the shortest path between all pairs of vertices where intermediate vertices are restricted to a given set. It does this using a bottom-up computation in O(V^3) time and O(V^2) space.
Part of Lecture Series on Automatic Control Systems delivered by me to Final year Diploma in Engg. Students. Equally useful for higher level. Easy language and step by step procedure for drawing Bode Plots. Three illustrative examples are included.
Dijkstra's algorithm finds the shortest paths from a source node to all other nodes in a graph. It works by maintaining two sets - one for nodes whose shortest paths are determined, and one for remaining nodes. It iteratively selects the node with the smallest distance from the source, calculates the distances to its neighbors, and moves them to the determined set until all nodes are processed. Some applications include finding fastest routes in transportation networks like road maps or flight schedules.
This document presents information about the shortest path problem in graphs. It defines key graph terms like vertices, edges, and discusses weighted, directed, and undirected graphs. It provides an example of finding the shortest path between two vertices in a graph using Dijkstra's algorithm and walks through the steps of running the algorithm on a sample graph to find the shortest path between vertices 1 and 9.
Dijkstra's algorithm is a link-state routing algorithm that computes the least-cost paths from one node to all other nodes in a network. It works by iteratively building a set N' of nodes whose least-cost paths are known, starting from a source node. In each iteration, it finds the node w not in N' with the minimum path cost and updates the cost estimates to nodes adjacent to w. This process repeats until all nodes are in N', providing the shortest path forwarding table for the source node. The algorithm runs in O(n^2) time for n nodes but more efficient implementations exist. Oscillations can potentially occur if link costs change based on traffic loads.
The document discusses the shortest path problem and Dijkstra's algorithm for solving it in graphs with non-negative edge weights. It defines the shortest path problem, explains that it is well-defined for non-negative graphs but not graphs with negative edge weights or cycles. It then describes Dijkstra's algorithm, how it works by iteratively finding the shortest path from the source to each vertex, and provides pseudocode for its implementation.
This document describes breadth-first search (BFS) graph algorithms. It begins by defining graphs and different graph representations. It then explains BFS, which explores a graph by exploring all of the neighbor nodes of the starting node, then all of the neighbors of the neighbors, and so on outwards in "waves" or breadth-first manner. The document provides pseudocode for BFS and walks through an example run on a sample graph to demonstrate how BFS works. It concludes by discussing the running time of BFS and providing an example programming assignment for implementing BFS.
1) The document discusses various linear transformations including reflection, rotation, and shear applied to geometric shapes like triangles and rectangles.
2) Reflection is illustrated for a triangle across the x-axis and y=-x line. Rotation is shown counterclockwise for different triangles around the origin.
3) Clockwise rotation and shear transformations in the x-direction are also demonstrated through examples using matrices applied to triangle and rectangle vertices. Plots of the transformed shapes are provided.
The document defines topological sorting as a linear ordering of the vertices in a directed acyclic graph (DAG) such that if there is a path from vertex vi to vk, then vi appears before vk in the ordering. It provides an algorithm for finding a topological sort by initializing an array, finding vertices of degree zero, adding them to the array, and removing outgoing edges. It also describes an algorithm for enumerating all possible topological sorts by computing indegree counts and pushing vertices with indegree of zero onto a stack.
This chapter discusses different types of graphs including undirected graphs, directed graphs, and weighted graphs. It describes common graph terminology like vertices, edges, paths, cycles, and trees. It also covers common graph algorithms like breadth-first search, depth-first search, minimum spanning trees, and shortest paths. Finally, it discusses strategies for implementing graphs using adjacency lists and adjacency matrices.
Skiena algorithm 2007 lecture10 graph data strctureszukun
This document summarizes different types of graph data structures and representations. It discusses graphs as consisting of vertices and edges, and describes properties like directed vs undirected, weighted vs unweighted, sparse vs dense. It also covers different representations like adjacency matrices and lists, and provides code examples for initializing, reading, and inserting edges into a graph represented using an adjacency list.
Basic Mathematics (PPISMP) - representing data into bar graphT-ah Atirah
The document discusses representing income data from a store in Kuala Terengganu, Malaysia from 2003-2005 using bar graphs. It provides the store's annual total revenues, expenses, and profits. A vertical bar graph, horizontal bar graph, and pie chart could be used. Key information that can be gleaned from the graphs is the highest and lowest revenues, expenses, and profits by year, and differences in amounts between years. Total profits were RM70,150 over the three years, with the highest in 2004 at RM26,101 and lowest in 2005 at RM18,402.
This document discusses trees and tree traversal algorithms. It defines trees and forests, and introduces spanning trees and spanning forests. It then discusses ordered rooted trees and the three tree traversal algorithms: preorder, inorder, and postorder. Preorder traverses the root first, then left subtree, then right subtree. Inorder traverses left subtree, then root, then right subtree. Postorder traverses left subtree, then right subtree, then root. Examples of each traversal type on sample trees are provided.
This document discusses topological sorting of student activities. It describes how a student has various activities that need to be organized. Topological sorting algorithms can systematically sort the order of activities. The document provides an example of a student's activity graph and explains how to perform topological sorting on this graph using an algorithm. It describes computing indegrees, finding a vertex with indegree 0, removing that vertex and updating indegrees, repeating until all vertices are processed. Finally, it analyzes the complexity of this algorithm as O(V^2 + E) time.
This document provides an overview of advanced data structures and algorithm analysis taught by Dr. Sukhamay Kundu at Louisiana State University. It discusses the role of data structures in making computations faster by supporting efficient data access and storage. The document distinguishes between algorithms, which determine the computational steps and data access order, and data structures, which enable efficient reading and writing of data. It also describes different methods for measuring algorithm performance, such as theoretical time complexity analysis and empirical measurements. Examples are provided for instrumenting code to count operations. Overall, the document introduces fundamental concepts about algorithms and data structures.
Mathematics (from Greek μάθημα máthēma, “knowledge, study, learning”) is the study of topics such as quantity (numbers), structure, space, and change. There is a range of views among mathematicians and philosophers as to the exact scope and definition of mathematics
Simple algorithm & hopcroft karp for bipartite graphMiguel Pereira
The document discusses algorithms for maximum matchings in bipartite graphs. It defines bipartite graphs and matchings. A simple algorithm finds augmenting paths and increments the matching size in each iteration, having complexity O(VE). The more efficient Hopcroft-Karp algorithm finds a maximal set of shortest augmenting paths and augments along all paths simultaneously in each iteration, achieving complexity O(√V√E). It demonstrates the algorithm augmenting the matching by alternating along paths in the maximal set.
The document discusses different matrix representations of graphs:
1) Incidence matrix shows which edges are incident to each vertex with 1s and 0s.
2) Adjacency matrix shows which vertices are adjacent to each other with 1s and 0s.
3) Cut-set matrix shows which edges are part of given cut sets that disconnect the graph with 1s and 0s.
A graph consists of vertices and edges, where vertices represent entities and edges represent relationships between vertices. Graphs can be represented sequentially using matrices like adjacency and incidence matrices, or linked using data structures like adjacency lists. Adjacency matrices allow fast addition/removal of edges but use more memory, while adjacency lists use less memory but are slower to modify. The best representation depends on whether the graph is dense or sparse.
This document provides definitions and theorems related to graph theory. It begins with definitions of simple graphs, vertices, edges, degree, and the handshaking lemma. It then covers definitions and properties of paths, cycles, adjacency matrices, connectedness, Euler paths and circuits. The document also discusses Hamilton paths, planar graphs, trees, and other special types of graphs like complete graphs and bipartite graphs. It provides examples and proofs of many graph theory concepts and results.
This document provides information about graphs and graph algorithms. It discusses different graph representations including adjacency matrices and adjacency lists. It also describes common graph traversal algorithms like depth-first search and breadth-first search. Finally, it covers minimum spanning trees and algorithms to find them, specifically mentioning Kruskal's algorithm.
This document provides an overview of graphs and graph algorithms. It begins with an introduction to graphs, including definitions of vertices, edges, directed/undirected graphs, and graph representations using adjacency matrices and lists. It then covers graph traversal algorithms like depth-first search and breadth-first search. Minimum spanning trees and algorithms for finding them like Kruskal's algorithm are also discussed. The document provides examples and pseudocode for the algorithms. It analyzes the time complexity of the graph algorithms. Overall, the document provides a comprehensive introduction to fundamental graph concepts and algorithms.
The document discusses breadth-first search (BFS) algorithms for graphs. It explains that BFS runs in O(n^2) time on adjacency matrices due to checking all elements in each row, but in O(n+m) time on adjacency lists where m is the number of edges. It then describes how to modify BFS to record the shortest path between nodes using a predecessor array. The rest of the document provides examples of how BFS works and applications such as finding connected components and directed acyclic graphs.
The document defines and explains basic graph terminology and representations. It begins by defining what a graph is composed of, including vertices and edges. It then discusses directed vs undirected graphs and provides examples. It also covers basic graph terminology such as adjacent nodes, degree, paths, cycles, and more. Finally, it discusses different ways of representing graphs, including adjacency matrices, adjacency lists, and traversing graphs using breadth-first and depth-first search algorithms.
topologicalsort-using c++ as development language.pptxjanafridi251
topological sort using c++ as programming language to search through a tree structureknljhcffxgchjkjhlkjkfhdffxgchvjbknlkjhgchvjbkjxfghjhiyuighjbyfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffvgvvvvvvvvnbbbbbbbbbfuyfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg
This document discusses several graph algorithms:
1) Topological sort is an ordering of the vertices of a directed acyclic graph (DAG) such that for every edge from vertex u to v, u comes before v in the ordering. It can be used to find a valid schedule respecting dependencies.
2) Strongly connected components are maximal subsets of vertices in a directed graph such that there is a path between every pair of vertices. An algorithm uses depth-first search to find SCCs in linear time.
3) Minimum spanning trees find a subset of edges that connects all vertices at minimum total cost. Prim's and Kruskal's algorithms find minimum spanning trees using greedy strategies in O(E
Algorithms and data Chapter 3 V Graph.pptxzerihunnana
This document discusses graphs and graph algorithms. It defines graphs as collections of vertices and edges. It describes different types of graphs like directed, undirected, weighted graphs. It explains graph traversal algorithms like breadth-first search and depth-first search. It also discusses minimum spanning trees and algorithms to find them, like Prim's algorithm and Kruskal's algorithm.
01-05-2023, SOL_DU_MBAFT_6202_Dijkstra’s Algorithm Dated 1st May 23.pdfDKTaxation
Dijkstra's algorithm is used to find the shortest paths between nodes in a graph. It works by growing the shortest path tree one vertex at a time. It begins at the source node and examines all neighboring nodes, updating paths and tracking predecessors until the shortest path to every node has been determined. The Ford-Fulkerson method finds the maximum flow in a flow network by iteratively augmenting the flow along paths with available residual capacity until no more flow is possible. It works to push flow from the source to the sink along paths with available capacity until the network is saturated.
The document discusses algorithms for computing convex hulls, including Graham's scan and quickhull algorithms. Graham's scan finds the convex hull of a set of points by maintaining a stack of candidate points and removing points that are not vertices of the convex hull. It runs in O(n log n) time. Quickhull is a divide and conquer algorithm that recursively partitions points and computes farthest points to partition the space until the convex hull is completed. Both algorithms are efficient ways to compute convex hulls in two dimensions.
Graph theory is the study of graphs, which are mathematical structures used to model pairwise relations between objects. A graph consists of vertices and edges connecting pairs of vertices. There are many types of graphs including trees, which are connected acyclic graphs. Spanning trees are subgraphs of a graph that connect all vertices using the minimum number of edges. Key concepts in graph theory include paths, connectedness, cycles, and isomorphism between graphs.
The document discusses algorithms for solving the range minimum query (RMQ) problem. It first reduces RMQ to the lowest common ancestor (LCA) problem in trees. It then presents several algorithms for solving RMQ, including:
1. A trivial preprocessing algorithm that requires O(n^2) time and O(1) query time
2. The sparse table (ST) algorithm that requires O(n log n) preprocessing time and O(1) query time
3. An improved algorithm that partitions the array into blocks and requires O(n) preprocessing time and O(1) query time for queries spanning multiple blocks
4. A general O(n) time solution that builds a Cartesian tree from
The document discusses randomized graph algorithms and techniques for analyzing them. It describes a linear time algorithm for finding minimum spanning trees (MST) that samples edges and uses Boruvka's algorithm and edge filtering. It also discusses Karger's algorithm for approximating the global minimum cut in near-linear time using edge contractions. Finally, it presents an approach for 3-approximate distance oracles that preprocesses a graph to build a data structure for answering approximate shortest path queries in constant time using landmark vertices and storing local and global distance information.
The document discusses Boolean algebra and logic gates. It defines logic gates, explains their operations, and provides their logic symbols and truth tables. The types of logic gates covered are AND, OR, NOT, NOR, NAND, XOR, and XNOR. It also discusses sequential logic circuits like flip-flops, providing details on SR, JK, T, and D flip-flops including how to build them using logic gates. Additional topics covered include the difference between combinational and sequential logic circuits, Boolean theorems, sum-of-products and product-of-sums expressions, and the Karnaugh map method for simplifying logic expressions.
CS-102 Data Structure lectures on Graphsssuser034ce1
The document defines and explains various graph concepts:
- It describes graph representations like adjacency matrices and lists, and types of graphs like undirected, directed, and weighted.
- Key graph terminology is introduced such as vertices, edges, paths, cycles, connectedness, subgraphs, and degrees of vertices.
- Examples are provided to illustrate concepts like complete graphs, trees, and bipartite graphs.
- Graph representations like adjacency matrices and linked/packed adjacency lists are also summarized.
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingCeline George
The Accounting module in Odoo 17 is a complete tool designed to manage all financial aspects of a business. Odoo offers a comprehensive set of tools for generating financial and tax reports, which are crucial for managing a company's finances and ensuring compliance with tax regulations.
Real GitHub Copilot Exam Dumps for SuccessMark Soia
Download updated GitHub Copilot exam dumps to boost your certification success. Get real exam questions and verified answers for guaranteed performance
Contact Lens:::: An Overview.pptx.: OptometryMushahidRaza8
A comprehensive guide for Optometry students: understanding in easy launguage of contact lens.
Don't forget to like,share and comments if you found it useful!.
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetSritoma Majumder
Introduction
All the materials around us are made up of elements. These elements can be broadly divided into two major groups:
Metals
Non-Metals
Each group has its own unique physical and chemical properties. Let's understand them one by one.
Physical Properties
1. Appearance
Metals: Shiny (lustrous). Example: gold, silver, copper.
Non-metals: Dull appearance (except iodine, which is shiny).
2. Hardness
Metals: Generally hard. Example: iron.
Non-metals: Usually soft (except diamond, a form of carbon, which is very hard).
3. State
Metals: Mostly solids at room temperature (except mercury, which is a liquid).
Non-metals: Can be solids, liquids, or gases. Example: oxygen (gas), bromine (liquid), sulphur (solid).
4. Malleability
Metals: Can be hammered into thin sheets (malleable).
Non-metals: Not malleable. They break when hammered (brittle).
5. Ductility
Metals: Can be drawn into wires (ductile).
Non-metals: Not ductile.
6. Conductivity
Metals: Good conductors of heat and electricity.
Non-metals: Poor conductors (except graphite, which is a good conductor).
7. Sonorous Nature
Metals: Produce a ringing sound when struck.
Non-metals: Do not produce sound.
Chemical Properties
1. Reaction with Oxygen
Metals react with oxygen to form metal oxides.
These metal oxides are usually basic.
Non-metals react with oxygen to form non-metallic oxides.
These oxides are usually acidic.
2. Reaction with Water
Metals:
Some react vigorously (e.g., sodium).
Some react slowly (e.g., iron).
Some do not react at all (e.g., gold, silver).
Non-metals: Generally do not react with water.
3. Reaction with Acids
Metals react with acids to produce salt and hydrogen gas.
Non-metals: Do not react with acids.
4. Reaction with Bases
Some non-metals react with bases to form salts, but this is rare.
Metals generally do not react with bases directly (except amphoteric metals like aluminum and zinc).
Displacement Reaction
More reactive metals can displace less reactive metals from their salt solutions.
Uses of Metals
Iron: Making machines, tools, and buildings.
Aluminum: Used in aircraft, utensils.
Copper: Electrical wires.
Gold and Silver: Jewelry.
Zinc: Coating iron to prevent rusting (galvanization).
Uses of Non-Metals
Oxygen: Breathing.
Nitrogen: Fertilizers.
Chlorine: Water purification.
Carbon: Fuel (coal), steel-making (coke).
Iodine: Medicines.
Alloys
An alloy is a mixture of metals or a metal with a non-metal.
Alloys have improved properties like strength, resistance to rusting.
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...larencebapu132
This is short and accurate description of World war-1 (1914-18)
It can give you the perfect factual conceptual clarity on the great war
Regards Simanchala Sarab
Student of BABed(ITEP, Secondary stage)in History at Guru Nanak Dev University Amritsar Punjab 🙏🙏
What makes space feel generous, and how architecture address this generosity in terms of atmosphere, metrics, and the implications of its scale? This edition of #Untagged explores these and other questions in its presentation of the 2024 edition of the Master in Collective Housing. The Master of Architecture in Collective Housing, MCH, is a postgraduate full-time international professional program of advanced architecture design in collective housing presented by Universidad Politécnica of Madrid (UPM) and Swiss Federal Institute of Technology (ETH).
Yearbook MCH 2024. Master in Advanced Studies in Collective Housing UPM - ETH
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schoolsdogden2
Algebra 1 is often described as a “gateway” class, a pivotal moment that can shape the rest of a student’s K–12 education. Early access is key: successfully completing Algebra 1 in middle school allows students to complete advanced math and science coursework in high school, which research shows lead to higher wages and lower rates of unemployment in adulthood.
Learn how The Atlanta Public Schools is using their data to create a more equitable enrollment in middle school Algebra classes.
Understanding P–N Junction Semiconductors: A Beginner’s GuideGS Virdi
Dive into the fundamentals of P–N junctions, the heart of every diode and semiconductor device. In this concise presentation, Dr. G.S. Virdi (Former Chief Scientist, CSIR-CEERI Pilani) covers:
What Is a P–N Junction? Learn how P-type and N-type materials join to create a diode.
Depletion Region & Biasing: See how forward and reverse bias shape the voltage–current behavior.
V–I Characteristics: Understand the curve that defines diode operation.
Real-World Uses: Discover common applications in rectifiers, signal clipping, and more.
Ideal for electronics students, hobbyists, and engineers seeking a clear, practical introduction to P–N junction semiconductors.
How to manage Multiple Warehouses for multiple floors in odoo point of saleCeline George
The need for multiple warehouses and effective inventory management is crucial for companies aiming to optimize their operations, enhance customer satisfaction, and maintain a competitive edge.
*Metamorphosis* is a biological process where an animal undergoes a dramatic transformation from a juvenile or larval stage to a adult stage, often involving significant changes in form and structure. This process is commonly seen in insects, amphibians, and some other animals.
How to Set warnings for invoicing specific customers in odooCeline George
Odoo 16 offers a powerful platform for managing sales documents and invoicing efficiently. One of its standout features is the ability to set warnings and block messages for specific customers during the invoicing process.
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...Celine George
Analytic accounts are used to track and manage financial transactions related to specific projects, departments, or business units. They provide detailed insights into costs and revenues at a granular level, independent of the main accounting system. This helps to better understand profitability, performance, and resource allocation, making it easier to make informed financial decisions and strategic planning.
3. Connectivity
• A graph is connected if and only if there exists a path
between every pair of distinct vertices.
• A graph is connected if and only if there exists a simple
path between every pair of distinct vertices (since every
non-simple path contains a cycle, which can be bypassed)
• How to check for connectivity?
• Run BFS or DFS (using an arbitrary vertex as the source)
• If all vertices have been visited, the graph is connected.
• Running time? O(n + m)
3
6. Connected Components
• Formally stated:
• A connected component is a maximal connected subgraph of
a graph.
• The set of connected components is unique for a given graph.
6
7. Finding Connected Components
For each vertex
Call DFS
This will find
all vertices
connected
to “v” => one
connected component
Basic DFS algorithm.
If not visited
7
8. Time Complexity
• Running time for each i connected component
• Question:
• Can two connected components have the same edge?
• Can two connected components have the same vertex?
• So:
)( ii mnO
i
i
i
i
i
ii mnOmnOmnO )()()(
8
9. Trees
• Tree arises in many computer science applications
• A graph G is a tree if and only if it is connected and acyclic
(Acyclic means it does not contain any simple cycles)
• The following statements are equivalent
• G is a tree
• G is acyclic and has exactly n-1 edges
• G is connected and has exactly n-1 edges
9
10. Tree as a (directed) Graph
15
6 18
3 8 30
16
Is it a graph?
Does it contain cycles?
(in other words, is it acyclic)
How many vertices?
How many edges?
10
11. Directed Graph
• A graph is directed if direction is assigned to each
edge. We call the directed edges arcs.
• An edge is denoted as an ordered pair (u, v)
• Recall: for an undirected graph
• An edge is denoted {u,v}, which actually corresponds to two
arcs (u,v) and (v,u)
11
13. Directed Acyclic Graph
• A directed path is a sequence of vertices
(v0, v1, . . . , vk)
• Such that (vi, vi+1) is an arc
• A directed cycle is a directed path such that the first
and last vertices are the same.
• A directed graph is acyclic if it does not contain any
directed cycles
13
14. Indegree and Outdegree
• Since the edges are directed
• We can’t simply talk about Deg(v)
• Instead, we need to consider the arcs coming “in” and
going “out”
• Thus, we define terms
• Indegree(v)
• Outdegree(v)
14
15. Outdegree
• All of the arcs going “out” from v
• Simple to compute
• Scan through list Adj[v] and count the arcs
• What is the total outdegree? (m=#edges)
mv
v
vertex
)(outdegree
15
16. Indegree
• All of the arcs coming “in” to v
• Not as simple to compute as outdegree
• First, initialize indegree[v]=0 for each vertex v
• Scan through adj[v] list for each v
• For each vertex w seen, indegree[w]++;
• Running time: O(n+m)
• What is the total indegree?
mv
v
vertex
)(indegree
16
17. Indegree + Outdegree
• Each arc (u,v) contributes count 1 to the outdegree of
u and count 1 to the indegree of v.
mvv
v
)(outdegree)(indegree
vertex
17
19. Directed Graphs Usage
• Directed graphs are often used to represent order-
dependent tasks
• That is we cannot start a task before another task finishes
• We can model this task dependent constraint using arcs
• An arc (i,j) means task j cannot start until task i is finished
• Clearly, for the system not to hang, the graph must be
acyclic.
i j
Task j cannot start
until task i is finished
19
20. Topological Sort
• Topological sort is an algorithm for a directed acyclic
graph
• It can be thought of as a way to linearly order the
vertices so that the linear order respects the ordering
relations implied by the arcs
0
1
2
3
4
5
6
7
8
9
For example:
0, 1, 2, 5, 9
0, 4, 5, 9
0, 6, 3, 7 ?
20
21. Topological Sort
• Idea:
• Starting point must have zero indegree!
• If it doesn’t exist, the graph would not be acyclic
1. A vertex with zero indegree is a task that can start
right away. So we can output it first in the linear
order
2. If a vertex i is output, then its outgoing arcs (i, j) are
no longer useful, since tasks j does not need to wait
for i anymore- so remove all i’s outgoing arcs
3. With vertex i removed, the new graph is still a
directed acyclic graph. So, repeat step 1-2 until no
vertex is left.
21
43. Topological Sort: Complexity
• We never visited a vertex more than one time
• For each vertex, we had to examine all outgoing edges
• Σ outdegree(v) = m
• This is summed over all vertices, not per vertex
• So, our running time is exactly
• O(n + m)
43
46. Outline and Reading
• Minimum Spanning Trees
• Definitions
• A crucial fact
• The Prim-Jarnik Algorithm
• Kruskal's Algorithm
46
47. Reminder:
Weighted Graphs
• In a weighted graph, each edge has an associated numerical value,
called the weight of the edge
• Edge weights may represent, distances, costs, etc.
• Example:
• In a flight route graph, the weight of an edge represents the distance in miles
between the endpoint airports
47
ORD
PVD
MIA
DFW
SFO
LAX
LGA
HNL
48. Spanning Subgraph and Spanning Tree
• Spanning subgraph
•Subgraph of a graph G
containing all the vertices of G
• Spanning tree
• Spanning subgraph that is itself a (free) tree
• So what is minimum spanning Tree ?
48
ORD
PIT
ATL
STL
DEN
DFW
DCA
10
1
9
8
6
3
25
7
4
49. Minimum Spanning Tree
• A spanning tree of a connected graph is a tree
containing all the vertices.
• A minimum spanning tree (MST) of a weighted
graph is a spanning tree with the smallest weight.
• The weight of a spanning tree is the sum of the
edge weights.
• Graph and its spanning trees: Tree 2 is the minimum spanning tree 49
50. MST Origin
• Otakar Boruvka (1926).
• Electrical Power Company of Western Moravia in Brno.
• Most economical construction of electrical power network.
• Concrete engineering problem is now a cornerstone
problem-solving model in combinatorial optimization.
50
51. Applications
• MST is fundamental problem with diverse applications.
• Network design.
• telephone, electrical, hydraulic, TV cable, computer, road
• Approximation algorithms for NP-hard problems.
traveling salesperson problem, Steiner tree
• Transportation networks
• Indirect applications.
max bottleneck paths
LDPC codes for error correction
image registration with Renyi entropy
learning salient features for real-time face verification
reducing data storage in sequencing amino acids in a protein
model locality of particle interactions in turbulent fluid flows
autoconfig protocol for Ethernet bridging to avoid cycles in a network
51
55. MST aka SST
• Remark: The minimum spanning tree may not be
unique. However, if the weights of all the edges are
pairwise distinct, it is indeed unique (we won’t prove
this now).
Example
55
56. Minimum Spanning Tree Problem
• MST Problem: Given a connected weighted undirected
Graph G, design an algorithm that outputs a minimum
spanning tree (MST) of G
• Two Greedy algorithms
• Prim’s algorithm
• Kruskal's Algorithm
• What is Greedy algorithm ?
An algorithm that always takes the best immediate, or local, solution
while finding an answer. Greedy algorithms find the overall, or
globally, optimal solution for some optimal problems, but may find
less-than-optimal solutions for some instances of other problems.
56
57. Greedy Algorithm
• Greedy algorithms is a technique for solving problems with
the following properties:
• The problem is an optimization problem, to find the solution
that minimizes or maximizes some value (cost/profit).
• The solution can be constructed in a sequence of
steps/choices.
• For each choice point:
• The choice must be feasible.
• The choice looks as good or better than alternatives.
• The choice cannot be revoked.
57
58. Greedy Algorithm cont’d…
Example of Making Change
• Suppose we want to give change of a certain amount (say
24 cents).
• We would like to use fewer coins rather than more.
• We can make a solution by repeatedly choosing
a coin <= to the current amount, resulting in a new mount.
• The greedy solution is to always choose the largest coin
value possible (for 24 cents: 10, 10, 1, 1, 1, 1).
• If there were an 8-cent coin, the greedy algorithm would
not be optimal (but not bad). 58
59. Exercise: MST
Show an MST of the following graph.
59
ORD
PVD
MIA
DFW
SFO
LAX
LGA
HNL
60. Cycle Property
Cycle Property:
• Let T be a minimum
spanning tree of a
weighted graph G
• Let e be an edge of G that
is not in T and C let be the
cycle formed by e with T
• For every edge f of C,
weight(f) weight(e)
Proof:
• By contradiction
• If weight(f) > weight(e) we
can get a spanning tree of
smaller weight by replacing
e with f
60
8
4
2
3
6
7
7
9
8
e
C
f
8
4
2
3
6
7
7
9
8
C
e
f
Replacing f with e yields
a better spanning tree
61. Partition Property
Partition Property:
• Consider a partition of the vertices of
G into subsets U and V
• Let e be an edge of minimum weight
across the partition
• There is a minimum spanning tree of
G containing edge e
Proof:
• Let T be an MST of G
• If T does not contain e, consider the
cycle C formed by e with T and let f be
an edge of C across the partition
• By the cycle property,
weight(f) weight(e)
• Thus, weight(f) weight(e)
• We obtain another MST by replacing f
with e 61
U V
7
4
2
8
5
7
3
9
8 e
f
7
4
2
8
5
7
3
9
8 e
f
Replacing f with e yields
another MST
U V
62. Prim-Jarnik’s Algorithm
• (Similar to Dijkstra’s algorithm, for a connected graph)
• We pick an arbitrary vertex s and we grow the MST as a
cloud of vertices, starting from s
• Start with any vertex s and greedily grow a tree T
from s. At each step, add the cheapest edge to T that has
exactly one endpoint in T.
• We store with each vertex v a label d(v) = the smallest
weight of an edge connecting v to a vertex in the cloud
62
• At each step:
• We add to the cloud the
vertex u outside the cloud
with the smallest distance
label
• We update the labels of the
vertices adjacent to u
63. More Detail
• Step 0: choose any element r; set S={ r } and A=ø
(Take r as the root of our spanning tree)
• Step 1: Find a lightest edge such that one endpoint in
S and the other is in VS. Add this edge to A and its
other endpoint to S.
• Step 2: if VS=ø, then stop & output (minimum)
spanning tree (S,A). Otherwise go to step 1.
• The idea: expand the current tree by adding the
lightest (shortest) edge leaving it and its endpoint.
63
73. Exercise: Prim’s MST alg
• Show how Prim’s MST algorithm works on the following graph,
assuming you start with SFO, I.e., s=SFO.
• Show how the MST evolves in each iteration (a separate figure for each
iteration).
73
ORD
PVD
MIA
DFW
SFO
LAX
LGA
HNL
74. 74
Kruskal’s Algorithm
• priority queue stores the
edges outside the cloud
• Key: weight
• Element: edge
• At the end of the
algorithm
• We are left with one
cloud that encompasses
the MST
• A tree T which is our
MST
Algorithm KruskalMST(G)
for each vertex V in G do
define a Cloud(v) of {v}
let Q be a priority queue.
Insert all edges into Q using their
weights as the key
T
while T has fewer than n-1 edges
edge e = T.removeMin()
Let u, v be the endpoints of e
if Cloud(v) Cloud(u) then
Add edge e to T
Merge Cloud(v) and Cloud(u)
return T
Consider edges in ascending order of weight:
Add to tree unless it would create a cycle.
75. Data Structure for Kruskal Algortihm
• The algorithm maintains a forest of trees
• An edge is accepted it if connects distinct trees
• We need a data structure that maintains a partition,
i.e., a collection of disjoint sets, with the operations:
• find(u): return the set storing u
• union(u,v): replace the sets storing u and v with their union
75
76. Representation of a Partition
• Each set is stored in a sequence
• Each element has a reference back to the set
• operation find(u) takes O(1) time, and returns the set of
which u is a member.
• in operation union(u,v), we move the elements of the
smaller set to the sequence of the larger set and update
their references
• the time for operation union(u,v) is min(nu,nv), where nu
and nv are the sizes of the sets storing u and v
• Whenever an element is processed, it goes into a
set of size at least double, hence each element is
processed at most log n times
76
77. Partition-Based Implementation
• A partition-based version of Kruskal’s Algorithm
performs cloud merges as unions and tests as finds.
77
Algorithm Kruskal(G):
Input: A weighted graph G.
Output: An MST T for G.
Let P be a partition of the vertices of G, where each vertex forms a separate set.
Let Q be a priority queue storing the edges of G, sorted by their weights
Let T be an initially-empty tree
while Q is not empty do
(u,v) Q.removeMinElement()
if P.find(u) != P.find(v) then
Add (u,v) to T
P.union(u,v)
return T
Running time: O((n+m) log n)
92. Exercise: Kruskal’s MST alg
• Show how Kruskal’s MST algorithm works on the following graph.
• Show how the MST evolves in each iteration (a separate figure for each
iteration).
92
ORD
PVD
MIA
DFW
SFO
LAX
LGA
HNL
103. Outline and Reading
• Weighted graphs
• Shortest path problem
• Shortest path properties
• Dijkstra’s algorithm
• Algorithm
• Edge relaxation
• The Bellman-Ford algorithm
• Shortest paths in DAGs
• All-pairs shortest paths
103
104. Weighted Graphs
• In a weighted graph, each edge has an associated numerical value,
called the weight of the edge
• Edge weights may represent, distances, costs, etc.
• Example:
• In a flight route graph, the weight of an edge represents the distance in miles
between the endpoint airports
104
ORD
PVD
MIA
DFW
SFO
LAX
LGA
HNL
105. Shortest Path Problem
• Given a weighted graph and two vertices u and v, we want to find a path
of minimum total weight between u and v.
• Length of a path is the sum of the weights of its edges.
• Example:
• Shortest path between Providence and Honolulu
• Applications
• Internet packet routing
• Flight reservations
• Driving directions
105
ORD
PVD
MIA
DFW
SFO
LAX
LGA
HNL
106. Shortest Path Problem
• If there is no path from v to u, we denote the distance
between them by d(v, u)=+
• What if there is a negative-weight cycle in the graph?
106
ORD
PVD
MIA
DFW
SFO
LAX
LGA
HNL
107. Shortest Path Properties
Property 1:
A subpath of a shortest path is itself a shortest path
Property 2:
There is a tree of shortest paths from a start vertex to all the other vertices
Example:
Tree of shortest paths from Providence
107
ORD
PVD
MIA
DFW
SFO
LAX
LGA
HNL
108. Dijkstra’s Algorithm
• The distance of a vertex
v from a vertex s is the
length of a shortest path
between s and v
• Dijkstra’s algorithm
computes the distances
of all the vertices from a
given start vertex s
(single-source shortest
paths)
• Assumptions:
• the graph is connected
• the edge weights are
nonnegative
• We grow a “cloud” of vertices,
beginning with s and eventually
covering all the vertices
• We store with each vertex v a
label D[v] representing the
distance of v from s in the
subgraph consisting of the cloud
and its adjacent vertices
• The label D[v] is initialized to
positive infinity
• At each step
• We add to the cloud the vertex u
outside the cloud with the
smallest distance label, D[v]
• We update the labels of the
vertices adjacent to u (i.e. edge
relaxation)
108
109. Single –Source Shortest –Paths Problem
• The Problem: Given a Graph with
positive edge weights G=(V,E)
and a distinguishing source vertex, s € V,
determine the distance and a shortest path
from the source vertex to every vertex in
the graph
109
112. Example
112
CB
A
E
D
F
0
428
48
7 1
2 5
2
3 9
CB
A
E
D
F
0
328
5 11
48
7 1
2 5
2
3 9
CB
A
E
D
F
0
328
5
8
48
7 1
2 5
2
3 9
CB
A
E
D
F
0
327
5 8
48
7 1
2 5
2
3 9
1. Pull in one of the vertices with red labels
2. The relaxation of edges updates the labels of
LARGER font size
114. Exercise: Dijkstra’s alg
• Show how Dijkstra’s algorithm works on the following
graph, assuming you start with SFO, I.e., s=SFO.
• Show how the labels are updated in each iteration (a
separate figure for each iteration).
114
ORD
PVD
MIA
DFW
SFO
LAX
LGA
HNL
115. Why Dijkstra’s Algorithm Works
• Dijkstra’s algorithm is based on the greedy
method. It adds vertices by increasing distance.
115
Suppose it didn’t find all shortest
distances. Let F be the first wrong
vertex the algorithm processed.
When the previous node, D, on the
true shortest path was considered,
its distance was correct.
But the edge (D,F) was relaxed at
that time!
Thus, so long as D[F]>D[D], F’s
distance cannot be wrong. That is,
there is no wrong vertex.
CB
s
E
D
F
0
327
5
8
48
7 1
2 5
2
3 9
116. Why It Doesn’t Work for Negative-
Weight Edges
116
Dijkstra’s algorithm is
based on the greedy
method. It adds
vertices by increasing
distance.
If a node with a
negative incident
edge were to be
added late to the
cloud, it could
mess up distances
for vertices already
in the cloud.
C’s true
distance is 1,
but it is already
in the cloud
with D[C]=2!
CB
A
E
D
F
0
428
48
7 -3
2 5
2
3 9
CB
A
E
D
F
0
028
5 11
48
7 -3
2 5
2
3 9
118. Bellman-Ford Algorithm
• Works even with negative-
weight edges
• Must assume directed
edges (for otherwise we
would have negative-weight
cycles)
• Iteration i finds all shortest
paths that use i edges.
• Running time: O(nm).
• Can be extended to detect a
negative-weight cycle if it
exists
• How?
118
Algorithm BellmanFord(G, s)
for all v G.vertices()
if v s
setDistance(v, 0)
else
setDistance(v, )
for i 1 to n-1 do
for each e G.edges()
{ relax edge e }
u G.origin(e)
z G.opposite(u,e)
r getDistance(u) weight(e)
if r < getDistance(z)
setDistance(z,r)
120. Exercise: Bellman-Ford’s alg
• Show how Bellman-Ford’s algorithm works on the
following graph, assuming you start with the top node
• Show how the labels are updated in each iteration (a
separate figure for each iteration).
120
0
48
7 1
-5 5
-2
3 9
121. DAG-based Algorithm
• Works even with
negative-weight edges
• Uses topological order
• Is much faster than
Dijkstra’s algorithm
• Running time: O(n+m).
121
Algorithm DagDistances(G, s)
for all v G.vertices()
if v s
setDistance(v, 0)
else
setDistance(v, )
Perform a topological sort of the vertices
for u 1 to n do {in topological order}
for each e G.outEdges(u)
{ relax edge e }
z G.opposite(u,e)
r getDistance(u) weight(e)
if r < getDistance(z)
setDistance(z,r)
123. Exercize: DAG-based Alg
• Show how DAG-based algorithm works on the
following graph, assuming you start with the second
rightmost node
• Show how the labels are updated in each iteration (a separate
figure for each iteration).
123
∞ 0 ∞ ∞∞ ∞
5 2 7 -1 -2
6 1
3 4
2
1
2
3
4
5
124. Summary of Shortest-Path Algs
• Breadth-First-Search
• Dijkstra’s algorithm
• Algorithm
• Edge relaxation
• The Bellman-Ford algorithm
• Shortest paths in DAGs
124
125. All-Pairs Shortest Paths
• Find the distance between
every pair of vertices in a
weighted directed graph
G.
• We can make n calls to
Dijkstra’s algorithm (if no
negative edges), which
takes O(nmlog n) time.
• Likewise, n calls to
Bellman-Ford would take
O(n2m) time.
• We can achieve O(n3)
time using dynamic
programming (similar to
the Floyd-Warshall
algorithm).
125
Algorithm AllPair(G) {assumes vertices 1,…,n}
for all vertex pairs (i,j)
if i j
D0[i,i] 0
else if (i,j) is an edge in G
D0[i,j] weight of edge (i,j)
else
D0[i,j] +
for k 1 to n do
for i 1 to n do
for j 1 to n do
Dk[i,j] min{Dk-1[i,j], Dk-1[i,k]+Dk-1[k,j]}
return Dn
k
j
i
Uses only vertices
numbered 1,…,k-1 Uses only vertices
numbered 1,…,k-1
Uses only vertices numbered 1,…,k
(compute weight of this edge)