contest algorithms january 2016 introduce the main kinds of graphs, discuss two implementation...

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

If you can't read please download the document

Upload: griffin-rodney-hunt

Post on 18-Jan-2018

217 views

Category:

Documents


0 download

DESCRIPTION

 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

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.