Contest Algorithms January 2016 Introduce the main kinds of graphs, discuss two implementation approaches, and remind you about trees 6. Intro. to Graphs.

Slides:



Advertisements
Similar presentations
CS 336 March 19, 2012 Tandy Warnow.
Advertisements

Chapter 9 Graphs.
CSE 373 Graphs 1: Concepts, Depth/Breadth-First Search
 Graph Graph  Types of Graphs Types of Graphs  Data Structures to Store Graphs Data Structures to Store Graphs  Graph Definitions Graph Definitions.
1 Representing Graphs. 2 Adjacency Matrix Suppose we have a graph G with n nodes. The adjacency matrix is the n x n matrix A=[a ij ] with: a ij = 1 if.
Graph & BFS.
CSC 213 ORD DFW SFO LAX Lecture 20: Graphs.
© 2004 Goodrich, Tamassia Graphs1 ORD DFW SFO LAX
Lists A list is a finite, ordered sequence of data items. Two Implementations –Arrays –Linked Lists.
1 Graphs ORD DFW SFO LAX Many slides taken from Goodrich, Tamassia 2004.
1 Data Structures and Algorithms Graphs I: Representation and Search Gal A. Kaminka Computer Science Department.
1 Graphs: Concepts, Representation, and Traversal CSC401 – Analysis of Algorithms Lecture Notes 13 Graphs: Concepts, Representation, and Traversal Objectives:
Graphs1 Part-H1 Graphs ORD DFW SFO LAX
Graphs1 ORD DFW SFO LAX Graphs2 Outline and Reading Graphs (§6.1) Definition Applications Terminology Properties ADT Data structures.
Graphs1 ORD DFW SFO LAX Graphs2 Outline and Reading Graphs (§6.1) Definition Applications Terminology Properties ADT Data structures.
ECE669 L10: Graph Applications March 2, 2004 ECE 669 Parallel Computer Architecture Lecture 10 Graph Applications.
Important Problem Types and Fundamental Data Structures
Discrete Mathematics Lecture 9 Alexander Bukharovich New York University.
GRAPH Learning Outcomes Students should be able to:
Chapter 9 – Graphs A graph G=(V,E) – vertices and edges
Spring 2015 Lecture 10: Elementary Graph Algorithms
Computer Science 112 Fundamentals of Programming II Introduction to Graphs.
Graph Dr. Bernard Chen Ph.D. University of Central Arkansas.
Graphs – ADTs and Implementations ORD DFW SFO LAX
Graphs Chapter 12.
Foundations of Discrete Mathematics
Week 11 - Wednesday.  What did we talk about last time?  Graphs  Euler paths and tours.
Tree A connected graph that contains no simple circuits is called a tree. Because a tree cannot have a simple circuit, a tree cannot contain multiple.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Graphs.
Module #19: Graph Theory: part II Rosen 5 th ed., chs. 8-9.
Elementary Graph Algorithms CLRS Chapter 22. Graph A graph is a structure that consists of a set of vertices and a set of edges between pairs of vertices.
Graphs CSE 2011 Winter June Graphs A graph is a pair (V, E), where  V is a set of nodes, called vertices  E is a collection of pairs.
Spring 2007Graphs1 ORD DFW SFO LAX
GRAPHS 1. Outline 2  Undirected Graphs and Directed Graphs  Depth-First Search  Breadth-First Search.
Discrete Structures Trees (Ch. 11)
ITEC 2620A Introduction to Data Structures Instructor: Prof. Z. Yang Course Website: 2620a.htm Office: TEL 3049.
Trees : Part 1 Section 4.1 (1) Theory and Terminology (2) Preorder, Postorder and Levelorder Traversals.
CSE 373: Data Structures and Algorithms
Graphs. Graphs Similar to the graphs you’ve known since the 5 th grade: line graphs, bar graphs, etc., but more general. Those mathematical graphs are.
Trees Dr. Yasir Ali. A graph is called a tree if, and only if, it is circuit-free and connected. A graph is called a forest if, and only if, it is circuit-free.
Discrete Structures CISC 2315 FALL 2010 Graphs & Trees.
7. Graph Traversal Describe and compare depth-first and breadth-first graph searching, and look at the creation of spanning trees Contest Algorithms: 7.
Contest Algorithms January 2016 Describe shortest path trees, SSSP, APSP, and three algorithms: Dijkstra, Bellman-Ford, Floyd-Warshall 9. Shortest Paths.
Chapter 9: Graphs.
Introduction to Graph Theory By: Arun Kumar (Asst. Professor) (Asst. Professor)
Discrete Maths 11. Graph Theory Objective
1 GRAPH Learning Outcomes Students should be able to: Explain basic terminology of a graph Identify Euler and Hamiltonian cycle Represent graphs using.
Chapter 11. Chapter Summary  Introduction to trees (11.1)  Application of trees (11.2)  Tree traversal (11.3)  Spanning trees (11.4)
Contest Algorithms January 2016 Describe a MST and the Prim and Kruskal algorithms for generating one. 8. Minimal Spanning Trees (MSTs) 1Contest Algorithms:
Programming Abstractions Cynthia Lee CS106B. Upcoming Topics Graphs! 1.Basics  What are they? How do we represent them? 2.Theorems  What are some things.
Contest Algorithms January 2016 Describe the maxflow problem, explain the Ford-Fulkerson, Edmonds-Karp algorithms. Look at the mincut problem, bipartite.
Graphs ORD SFO LAX DFW Graphs 1 Graphs Graphs
BCA-II Data Structure Using C Submitted By: Veenu Saini
Graphs 10/24/2017 6:47 AM Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and.
Graphs.
Graph Graphs and graph theory can be used to model:
Advanced Algorithms Analysis and Design
Discrete Maths 10. Trees 242/ , Semester 2, Objective
Chapter 1.
CS120 Graphs.
Graph Algorithms Using Depth First Search
CMSC 341 Lecture 21 Graphs (Introduction)
Discrete Maths 9. Graphs Objective
Graphs.
Graphs CSE 2011 Winter November 2018.
What is a Graph? a b c d e V= {a,b,c,d,e} E= {(a,b),(a,c),(a,d),
ITEC 2620M Introduction to Data Structures
Algorithms: Design and Analysis
Graphs G = (V, E) V are the vertices; E are the edges.
Important Problem Types and Fundamental Data Structures
Presentation transcript:

Contest Algorithms January 2016 Introduce the main kinds of graphs, discuss two implementation approaches, and remind you about trees 6. Intro. to Graphs 1Contest Algorithms: 6. Intro. to Graphs

 (Strongly) Connected Component  Sub Graph  Complete Graph  Directed Acyclic Graph (DAG)  Tree/Forest  Euler/Hamiltonian Path/Cycle  Bipartite Graph  Vertices/Nodes  Edges  Un/Weighted  Un/Directed  In/Out Degree  Self-Loop/Multiple Edges  Sparse/Dense  Path, Cycle  Isolated, Reachable 1. Graph Terms Contest Algorithms: 6. Graph Intro 2

 A graph has two parts (V, E), where:  V are the nodes, called vertices  E are the links between vertices, called edges ORD PVD MIA DFW SFO LAX LGA HNL

 Directed graph  the edges are directed  e.g., bus cost network  Undirected graph  the edges are undirected  e.g., road network

A weighted graph adds edge numbers a d e c b 2

 End vertices (or endpoints ) of an edge  U and V are the endpoints  Edges incident on a vertex  a, d, and b are incident  Adjacent vertices  U and V are adjacent  Degree of a vertex  X has degree 5  Parallel edges  h and i are parallel edges  Self-loop  j is a self-loop XU V W Z Y a c b e d f g h i j

 Path  sequence of alternating vertices and edges  begins with a vertex  ends with a vertex  each edge is preceded and followed by its endpoints  Simple path  path such that all its vertices and edges are distinct  Examples  P 1 =(V,b,X,h,Z) is a simple path  P 2 =(U,c,W,e,X,g,Y,f,W,d,V) is a path that is not simple P1P1 XU V W Z Y a c b e d f g hP2P2

 Cycle  circular sequence of alternating vertices and edges  each edge is preceded and followed by its endpoints  Simple cycle  cycle such that all its vertices and edges are distinct  Examples  C 1 =(V,b,X,g,Y,f,W,c,U,a) is a simple cycle  C 2 =(U,c,W,e,X,g,Y,f,W,d,V,a,) is a cycle that is not simple Graphs8 C1C1 XU V W Z Y a c b e d f g hC2C2

 A graph is connected if there is a path between every pair of vertices Connected graph Non connected graph with two connected components

Strong Connectivity  Each vertex can reach all other vertices 10Graphs a d c b e f g

 All pairs of vertices are connected by an edge.  No. of edges |E| = |V| (|V-1|)/2 = O(|V| 2 ) Complete Graphs 11

 Directed Acyclic Graph  no cycle  Eulerian Graph  must visit each edge once  Tree  connected, E = V?1, unique path!  Bipartite  2 sets, no edges within set! Some Competition Graphs 12

 A DAG has no cycles  Some algorithms become simpler when used on DAGs instead of general graphs, based on the principle of topological ordering  find shortest paths and longest paths by processing the vertices in a topological order Directed Acyclic Graph (DAG) Contest Algorithms13

 An Euler graph has either an Euler path or Euler tour.  An Euler path is defined as a path in a graph which visits each edge exactly once.  An Euler tour/cycle is an Euler path which starts and ends on the same vertex. Euler Graph Contest Algorithms: 6. Graph Intro14

 Search/traversal  visit every node once (Euler)  visit every edge once (Hamiltonian)  Shortest paths  Minimal Spanning Trees (MSTs)  Network flow  Matching  Graph coloring  Travelling salesman problem 2. Graph-related Problems Contest Algorithms: 6. Graph Intro15

 Adjacency matricies  if there is an edge from i to j then ai,j = 1, otherwise ai,j = 0.  Size: O(V 2 ); V, number of vertices  use with relatively low n and when the graph is dense (many edges)  Adjacency lists  Each node has a list of neighbors  O(V + E) (usually lower); E is the number of edges  use when the graph is sparse (few edges) 3. Implementing Graphs Contest Algorithms: 6. Graph Intro16

 Edges lists  A list of edges in the graph  O(2 * E) E is the number of edges  use when the graph is sparse (few edges) Contest Algorithms: 6. Graph Intro17

Examples Contest Algorithms: 6. Graph Intro18

Contest Algorithms: 6. Graph Intro19

Contest Algorithms: 6. Graph Intro20

3.1. Loading a Weighted Directed Graph Into an Adjacency Matrix (v.1) 1 Adj Matrix:

 Input data format:  no. of vertices  multiple lines, one for each vertex  each line: one number per vertex: 0 or a weight e.g Contest Algorithms: 6. Graph Intro22 see matData.txt

public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new File("matData.txt")); int numVs = sc.nextInt(); int[][] adjMat = new int[numVs][]; // use numVs as no. of rows for (int i = 0; i < numVs; i++) { adjMat[i] = new int[numVs]; // create ith row array with numVs as no. of columns for (int j = 0; j < numVs; j++) // fill row with weights adjMat[i][j] = sc.nextInt(); } printMatrix(adjMat); } // end of main() Code Contest Algorithms: 6. Graph Intro23 see UseAdjMatrix.java

public static void printMatrix(int[][] adjMat) { System.out.println("Adj Matrix:"); int numVs = adjMat.length; for (int i = 0; i < numVs; i++) { for (int j = 0; j < numVs; j++) System.out.printf(" %3d", adjMat[i][j]); System.out.println(); } System.out.println(); } // end of printMatrix() Contest Algorithms: 6. Graph Intro24

 Input data format:  no. of vertices, no. of edges  multiple lines, one for each edge  each line: (a b) weight e.g Contest Algorithms: 6. Graph Intro25 see mat2Data.txt This is a better input format for sparse graphs which have few edges Into an Adjacency Matrix (v.2)

public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new File("mat2Data.txt")); int numVs = sc.nextInt(); int numEs = sc.nextInt(); int[][] adjMat = new int[numVs][]; for (int i = 0; i < numVs; i++) adjMat[i] = new int[numVs]; for (int i = 0; i < numEs; i++) { int a = sc.nextInt(); int b = sc.nextInt(); int weight = sc.nextInt(); adjMat[a][b] = weight; } printMatrix(adjMat); // same as before } // end of main() Code Contest Algorithms: 6. Graph Intro26 see UseAdjMatrix2.java

3.2. Loading a Weighted Directed Graph Into an Adjacency List 1 Adj List: 0: (0, 2) (1, 3) (2, 1) 1: (3, 3) 2: (0, 3) (1, 2) (4, 2) 3: (2, 1) (4, 1) 4: (1, 1)

 Input data format:  no. of vertices  multiple lines, one for each vertex  each line: no. of pairs, list of (vertex, weight) pairs e.g Contest Algorithms: 6. Graph Intro28 see adjListData.txt

public String toString() { return "(" + x + ", " + y + ")"; } public int compareTo(IPair ip) { if (x != ip.getX()) return (x - ip.getX()); else return (y - ip.getY()); } // end of compareTo() } // end of IPair class public class IPair implements Comparable { private int x, y; public IPair(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } public void setX(int el) { x = el; } public void setY(int el) { y = el; } Storing a Pair of ints Contest Algorithms: 6. Graph Intro 29 see IPair.java

public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new File("adjListData.txt")); int numVs = sc.nextInt(); ArrayList > adjList = new ArrayList<>(numVs); // a list containing lists of (vertex, weight) pairs for (int i = 0; i < numVs; i++) // for each vertex adjList.add(new ArrayList<>()); // add a list to the list // fill each list with (vertex, weight) pairs for (ArrayList neigborList : adjList) { int numNeighbors = sc.nextInt(); // get no. of pairs for (int j = 0; j < numNeighbors; j++) neigborList.add( new IPair(sc.nextInt(), sc.nextInt())); // (vertex, weight) } printAdjList(adjList); } // end of main() Code Contest Algorithms: 6. Graph Intro30 see UseAdjList.java

public static void printAdjList( ArrayList > adjList) { System.out.println("Adj List:"); int vCount = 0; for (ArrayList neigborList : adjList) { System.out.print(vCount + ":"); for(IPair neigbour : neigborList) System.out.print(" " + neigbour); System.out.println(); vCount++; } System.out.println(); } // end of printAdjList() Contest Algorithms: 6. Graph Intro31

3.3. Loading a Weighted Directed Graph Into an Edges List 1 Edges List, sorted into decreasing weight: (3, 0, 1) (3, 1, 3) (3, 2, 0) (2, 0, 0) (2, 2, 1) (2, 2, 4) (1, 0, 2) (1, 3, 2) (1, 3, 4) (1, 4, 1)

 Input data format:  no. of edges  multiple lines, one for each edge  each line: (a, b) and weight, but data is stored weight, a, b e.g Contest Algorithms: 6. Graph Intro33 see elData.txt

public String toString() { return "(" + x +", "+ y +", "+ z + ")"; } public int compareTo(ITriple t) { if (x != t.getX()) return (t.getX() - x); // decreasing order by x // return (x - t.getX()); // increasing order by x else if (y != t.getY()) return (y - t.getY()); else return (z - t.getZ()); } // end of compareTo() } // end of ITriple class public class ITriple implements Comparable { private int x, y, z; public ITriple(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public int getX() { return x; } public int getY() { return y; } public int getZ() { return z; } public void setX(int el) { x = el; } public void setY(int el) { y = el; } public void setZ(int el) { z = el; } Storing a Triple of ints Contest Algorithms: 6. Graph Intro 34 see ITriple.java

public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new File("elData.txt")); int numEs = sc.nextInt(); PriorityQueue edgesList = new PriorityQueue<>(numEs); // priority queue of weighted edges; (weight, a, b) // build pri-queue of edges; (weight, a, b) for (int i = 0; i < numEs; i++) { int a = sc.nextInt(); int b = sc.nextInt(); // edge a-b int weight = sc.nextInt(); edgesList.offer( new ITriple(weight, a, b) ); } printEdgesList(edgesList); } // end of main() Code Contest Algorithms: 6. Graph Intro35 see UseEdgesList.java

public static void printEdgesList( PriorityQueue edgesList) { System.out.println("Edges List, sorted into decreasing weight: "); int numEs = edgesList.size(); for (int i = 0; i < numEs; i++) { ITriple wedge = edgesList.poll(); // weighted-edge pair System.out.println(" " + wedge); } } // end of printEdgesList() Contest Algorithms: 6. Graph Intro36

 Space  Adjacency Matrix  O( |V| 2 )  Adjacency List  O(|V|+|E|)  Edges List  O(2 * |E|)  Time  Find edge of vi and vj  Matrix (a ij )  O(1), List  O(|V|)  Find all edges of vi  List  O(|V|) but faster than matrix  O(|V|)  Dense graph : (many edges)  use an adj. matrix  Sparse graph : (few edges)  use an adj. list (or edges list ) 3.4. Space and Time Comparisons Contest Algorithms: 6. Graph Intro37

 A tree is a special graph. It is:  Connected  Has V vertices and exactly E = V ? 1 edges  Has no cycle  Has one unique path between two vertices  Sometimes, it has one special vertex called “root” (rooted tree): Root has no parent  A vertex in n-ary tree has either {0, 1,…,n} children  n = 2 is called binary tree 4. Trees Contest Algorithms: 6. Graph Intro38

 A (free) tree is an undirected graph T such that  T is connected  T has no cycles This definition of tree is different from the one of a rooted tree  A forest is an undirected graph without cycles  The connected components of a forest are trees Trees and Forests Graphs39 Tree Forest

e.g. Part of the ancient Greek god family: (Rooted) Tree Terminology Uranus AphroditeKronosAtlasPrometheus ErosZeusPoseidonHadesAres ApolloAthenaHermesHeracles levels ::::

Let T be a tree with root v 0. Suppose that x, y, z are verticies in T. (v 0, v 1,..., v n ) is a simple path in T (no loops). a) v n-1 is the parent of v n. b) v 0,..., v n-1 are ancestors of v n c) v n is a child of v n-1 Some Definitions continued

d) If x is an ancestor of y, then y is a descendant of x. e) If x and y are children of z, then x and y are siblings. f) If x has no children, then x is a terminal vertex (or a leaf ). g) If x is not a terminal vertex, then x is an internal (or branch ) vertex. continued

h) The subtree of T rooted at x is the graph with vertex set V and edge set E  V contains x and all the descendents of x  E = {e | e is an edge on a simple path from x to some vertex in V} i) The length of a path is the number of edges it uses, not verticies. continued

j) The level of a vertex x is the length of the simple path from the root to x. k) The height of a vertex x is the length of the simple path from x to the farthest leaf  the height of a tree is the height of its root l) A tree where every internal vertex has exactly m children is called a full m-ary tree.

The root is Uranus. A simple path is {Uranus, Aphrodite, Eros} The parent of Eros is Aphrodite. The ancestors of Hermes are Zeus, Kronos, and Uranus. The children of Zeus are Apollo, Athena, Hermes, and Heracles. Applied to the Example continued

The descendants of Kronos are Zeus, Poseidon, Hades, Ares, Apollo, Athena, Hermes, and Heracles. The leaves (terminal verticies) are Eros, Apollo, Athena, Hermes, Heracles, Poseidon, Hades, Ares, Atlas, and Prometheus. The branches (internal verticies) are Uranus, Aphrodite, Kronos, and Zeus. continued

The subtree rooted at Kronos: Kronos ZeusPoseidonHadesAres ApolloAthenaHermesHeracles continued

The length of the path {Uranus, Aphrodite, Eros} is 2 (not 3). The level of Ares is 2. The height of the tree is 3.