CS 1501
www.cs.pitt.edu/~nlf4/cs1501/
CS 1501 www.cs.pitt.edu/~nlf4/cs1501/ Union Find Dynamic - - PowerPoint PPT Presentation
CS 1501 www.cs.pitt.edu/~nlf4/cs1501/ Union Find Dynamic connectivity problem For a given graph G, can we determine whether or not two vertices are connected in G? Can also be viewed as checking subset membership Important for
www.cs.pitt.edu/~nlf4/cs1501/
vertices are connected in G?
2
item in the union/find structure
○ How do we determine if two vertices are connected? ○ How do we establish the connected components? ■ Add graph edges one at a time to UF data structure using union operations
3
5 3 4 2 1 6 7 U(2, 0) U(4, 7) U(1, 2) U(3, 2) U(4, 5) U(5, 7) U(6, 3) 1 2 3 4 5 6 1 2 3 4 5 6 ID: 7 7 4 1 1 3 3 3 4 6 6 6 6
4
○ To find if two vertices are connected? ○ For a union operation?
5
UF (int n) void union(int p, int q) int find (int p) boolean connected (int p, int q) int count()
Initialize with n items numbered 0 to n-1 Connect p with q Return id of the connected component that p is in True if p and q are connected Number of connected components
6
public int count() { return count; } public boolean connected(int p, int q) { return find(p) == find(q); }
7
public UF(int n) { count = n; id = new int[n]; for (int i = 0; i < n; i++) { id[i] = i; } } public int find(int p) { return id[p]; } public void union(int p, int q) { int pID = find(p), qID = find(q); if (pID == qID) return; for(int i = 0; i < id.length; i++) if (id[i] == pID) id[i] = qID; count--; }
8
used as a part of Kruskal’s algorithm?
○ What is the runtime of Kruskal’s algorithm?
9
1 3 2 4 5 6 5 1 5 5 3 2 4 6 6 PQ: 5: (0, 3) 6: (0, 1) 1: (0, 2) 3: (1, 4) 5: (1, 2) 5: (2, 3) 2: (3, 5) 4: (2, 5) 6: (2, 4) 6: (4, 5)
10
trees?
○ Each tree representing a different connected component ○ Every time a new connection is made, we simply make one tree the child of another
11
5 3 4 2 1 6 7 1 2 3 4 5 6 7 2 7 1 3
12
public int find(int p) { while (p != id[p]) p = id[p]; return p; } public void union(int p, int q) { int i = find(p); int j = find(q); if (i == j) return; id[i] = j; count--; }
13
○ find(): ■ Bound by the height of the tree ○ union(): ■ Bound by the height of the tree
○ Can we modify our approach to cap its max height?
14
5 3 4 2 1 6 7
15
1 2 3 4 5 6 7 2 7
public UF(int n) { count = n; id = new int[n]; sz = new int[n]; for (int i = 0; i < n; i++) { id[i] = i; sz[i] = 1; } } public void union(int p, int q) { int i = find(p), j = find(q); if (i == j) return; if (sz[i] < sz[j]) { id[i] = j; sz[j] += sz[i]; } else { id[j] = i; sz[i] += sz[j]; } count--; }
16
○ find()? ○ union()?
17
18
19
1 2 3 5 6 7 4 find(4) 4 5 4 find(0) 2