Beruflich Dokumente
Kultur Dokumente
1
Friday, May 10, 13 1
Types of Graph
Directed graph Undirected graph Weighted graph Unweighted graph Tree Directed Acyclic Graph (DAG)
2
Friday, May 10, 13 2
Graph representation
Adjacency matrix (2D Array) Adjacency list (vector of vector) Edge list (PQ of a struct of pair and int) Parent-Child Tree Structure (struct of int and
vector of int) Choice of data structure is important - it affects the time complexity
3
Friday, May 10, 13 3
Visit the children of a node rst before visiting the siblings Application: Topological sort, nding connected components in undirected graph Implementation: Standard library stack or recursion (Beware of stack overow) Sample problem: UVa 260, UVa 10369 Solution: (UVa 260)http://goo.gl/HlnA7
4
4
#define MAP_SIZE 10 int i, cur_node; bool graph[MAP_SIZE][MAP_SIZE]; //graph is a adjacency matrix //graph[i][j] is true if and only if nodes i and j are connected. //This array should be symmetrical about the diagonal. bool visited[MAP_SIZE]; //visited[i] is true when it is being visited stack<int> grey; memset(graph, 0, sizeof graph); memset(visited, 0, sizeof visited); //Set both graph and visited to be false grey.push(0); while (!grey.empty()) { cur_node = grey.top(); grey.pop(); if (visited[cur_node]) continue; visited[cur_node] = true; printf("%d\n", cur_node); for (i=0; i<MAP_SIZE; i++) if (graph[cur_node][i]) grey.push(i); } http://goo.gl/deuqI
Visit all the siblings of a node rst before visiting the children Application: Single source shortest path on unweighted graph Implementation: Standard library queue (Just replace all the stack in DFS to queue) Sample problem: UVa 336
6
6
Floyd-Warshall
int weight[SIZE][SIZE]; const int oo = int(1e9); int i, j, k; for (i=0; i<SIZE; i++) for (j=0; j<SIZE; j++) weight[i][j] = oo; //Get input for (k=0; k<SIZE; k++) for (i=0; i<SIZE; i++) for (j=0; j<SIZE; j++) weight[i][j] = min(weight[i][j], weight[i][k]+weight[k][j]); //weight now contains the shortest path between all points //Please take note of the order of the nested loops
8
Friday, May 10, 13 8
10
Friday, May 10, 13 10
DAG
Longest path in a DAG can be solved with
DP (LIS)
Top sort and nd the LIS on the sorted list Sample problem: UVa 103
11
Friday, May 10, 13 11
Topological Sort
For a directed graph G=(V, E), let u, v be all
possible nodes such that there is a directed node from u to v. u comes before v in the sorted sequence.
12
Friday, May 10, 13 12