Algorithms, 4 th Edition∙Robert Sedgewick and Kevin Wayne∙Copyright © 2002–2010∙ March 16, 2011 9:10:29 PM ‣ dynamic connectivity ‣ quick find ‣ quick.

Slides:



Advertisements
Similar presentations
Introduction to Algorithms Quicksort
Advertisements

Prof. Amr Goneid, AUC1 Analysis & Design of Algorithms (CSCE 321) Prof. Amr Goneid Department of Computer Science, AUC Part R4. Disjoint Sets.
Efficient access to TIN Regular square grid TIN Efficient access to TIN Let q := (x, y) be a point. We want to estimate an elevation at a point q: 1. should.
1 Union-find. 2 Maintain a collection of disjoint sets under the following two operations S 3 = Union(S 1,S 2 ) Find(x) : returns the set containing x.
CMSC 341 Binary Heaps Priority Queues. 8/3/2007 UMBC CSMC 341 PQueue 2 Priority Queues Priority: some property of an object that allows it to be prioritized.
Algorithms Analysis Lecture 6 Quicksort. Quick Sort Divide and Conquer.
1 Disjoint Sets Set = a collection of (distinguishable) elements Two sets are disjoint if they have no common elements Disjoint-set data structure: –maintains.
1 Introduction to Algorithms 6.046J/18.401J/SMA5503 Lecture 20 Prof. Erik Demaine.
EECS 311: Chapter 8 Notes Chris Riesbeck EECS Northwestern.
Algorithm and data structure. Overview Programming and problem solving, with applications Algorithm: method for solving a problem Data structure: method.
Union-Find: A Data Structure for Disjoint Set Operations
Disjoint Union / Find CSE 373 Data Structures Lecture 17.
CSE 326: Data Structures Disjoint Union/Find. Equivalence Relations Relation R : For every pair of elements (a, b) in a set S, a R b is either true or.
CSE 373, Copyright S. Tanimoto, 2002 Up-trees - 1 Up-Trees Review of the UNION-FIND ADT Straight implementation with Up-Trees Path compression Worst-case.
Chapter 7Louden, Programming Languages1 Chapter 7 - Control I: Expressions and Statements "Control" is the general study of the semantics of execution.
CS2420: Lecture 42 Vladimir Kulyukin Computer Science Department Utah State University.
Data Structures & Algorithms Union-Find Example Richard Newman.
1 HEAPS & PRIORITY QUEUES Array and Tree implementations.
Spring 2015 Lecture 11: Minimum Spanning Trees
Chapter 12 Recursion, Complexity, and Searching and Sorting
1 Programming with Recursion. 2 Recursive Function Call A recursive call is a function call in which the called function is the same as the one making.
Slides from Kevin Wayne on Union- Find and Percolotion.
Advanced Data Structure Hackson Leung
CSE373: Data Structures & Algorithms Lecture 11: Implementing Union-Find Aaron Bauer Winter 2014.
© Ronaldo Menezes, Florida Tech Fundamentals of Algorithmic Problem Solving  Algorithms are not answers to problems  They are specific instructions for.
CMSC 341 Disjoint Sets. 8/3/2007 UMBC CMSC 341 DisjointSets 2 Disjoint Set Definition Suppose we have an application involving N distinct items. We will.
Lossless Compression CIS 465 Multimedia. Compression Compression: the process of coding that will effectively reduce the total number of bits needed to.
CMSC 341 Disjoint Sets Textbook Chapter 8. Equivalence Relations A relation R is defined on a set S if for every pair of elements (a, b) with a,b  S,
Example Algorithms CSE 2320 – Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington 1.
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
Union-find Algorithm Presented by Michael Cassarino.
CSE373: Data Structures & Algorithms Lecture 11: Implementing Union-Find Nicki Dell Spring 2014.
CSE373: Data Structures & Algorithms Lecture 10: Implementing Union-Find Dan Grossman Fall 2013.
Fundamental Data Structures and Algorithms Peter Lee April 24, 2003 Union-Find.
Sorting: Implementation Fundamental Data Structures and Algorithms Klaus Sutner February 24, 2004.
COSC 2007 Data Structures II Chapter 13 Advanced Implementation of Tables IV.
1 The Disjoint Set ADT CS146 Chapter 8 Yan Qing Lei.
CS 146: Data Structures and Algorithms July 16 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
AVL Trees 1. 2 Outline Background Define balance Maintaining balance within a tree –AVL trees –Difference of heights –Rotations to maintain balance.
MA/CSSE 473 Days Answers to student questions Prim's Algorithm details and data structures Kruskal details.
0 Union-Find data structure. 1 Disjoint set ADT (also Dynamic Equivalence) The universe consists of n elements, named 1, 2, …, n n The ADT is a collection.
CHAPTER 8 THE DISJOINT SET ADT §1 Equivalence Relations 【 Definition 】 A relation R is defined on a set S if for every pair of elements (a, b), a, b 
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
WEEK 5 The Disjoint Set Class Ch CE222 Dr. Senem Kumova Metin
1 A Case Study: Percolation Percolation. Pour liquid on top of some porous material. Will liquid reach the bottom? Applications. [ chemistry, materials.
2.4 A Case Study: Percolation Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008.
CSE 373, Copyright S. Tanimoto, 2001 Up-trees - 1 Up-Trees Review of the UNION-FIND ADT Straight implementation with Up-Trees Path compression Worst-case.
Data Structures for Disjoint Sets Manolis Koubarakis Data Structures and Programming Techniques 1.
Data Structures for Disjoint Sets
Hash table CSC317 We have elements with key and satellite data
CSE 373, Copyright S. Tanimoto, 2001 Up-trees -
Lecture I Introduction
Disjoint Sets Chapter 8.
Compsci 201, Union-Find Algorithms
Course Outline Introduction and Algorithm Analysis (Ch. 2)
CMSC 341 Disjoint Sets Based on slides from previous iterations of this course.
i206: Lecture 14: Heaps, Graphs intro.
Data Structures & Algorithms Union-Find Example
Data Structures & Algorithms Union-Find Example
Lecture 2- Query Processing (continued)
Union-find algorithms
Union-Find.
CSE373: Data Structures & Algorithms Implementing Union-Find
Disjoint Sets DS.S.1 Chapter 8 Overview Dynamic Equivalence Classes
Disjoint Sets Textbook Chapter 8
2.4 A Case Study: Percolation
Heaps.
Disjoint Set Operations: “UNION-FIND” Method
Presentation transcript:

Algorithms, 4 th Edition∙Robert Sedgewick and Kevin Wayne∙Copyright © 2002–2010∙ March 16, :10:29 PM ‣ dynamic connectivity ‣ quick find ‣ quick union ‣ improvements ‣ applications 1.5 Union Find

2 Steps to developing a usable algorithm. Model the problem. Find an algorithm to solve it. Fast enough? Fits in memory? If not, figure out why. Find a way to address the problem. Iterate until satisfied. The scientific method. Mathematical analysis. Subtext of today’s lecture (and this course)

3 ‣ dynamic connectivity ‣ quick find ‣ quick union ‣ improvements ‣ applications

4 Given a set of objects Union: connect two objects. Connected: is there a path connecting the two objects? Dynamic connectivity union(3, 4) union(8, 0) union(2, 3) union(5, 6) connected(0, 2) no connected(2, 4) yes union(5, 1) union(7, 3) union(1, 6) connected(0, 2) yes connected(2, 4) yes union(4, 8) more difficult problem: find the path

5 Connectivity example p q Q. Is there a path from p to q? A. Yes.

6 Dynamic connectivity applications involve manipulating objects of all types. Pixels in a digital photo. Computers in a network. Variable names in Fortran. Friends in a social network. Transistors in a computer chip. Elements in a mathematical set. Metallic sites in a composite system. When programming, convenient to name sites 0 to N-1. Use integers as array index. Suppress details not relevant to union-find. Modeling the objects can use symbol table to translate from site names to integers: stay tuned (Chapter 3)

7 We assume "is connected to" is an equivalence relation: Reflexive: p is connected to p. Symmetric: if p is connected to q, then q is connected to p. Transitive: if p is connected to q and q is connected to r, then p is connected to r. Connected components. Maximal set of objects that are mutually connected. Modeling the connections { 0 } { } { } 3 connected components

8 Find query. Check if two objects are in the same component. Union command. Replace components containing two objects with their union. Implementing the operations union(2, 5) { 0 } { } { } 3 connected components { 0 } { } 2 connected components

9 Goal. Design efficient data structure for union-find. Number of objects N can be huge. Number of operations M can be huge. Find queries and union commands may be intermixed. Union-find data type (API) public class UF UF(int N) initialize union-find data structure with N objects (0 to N-1) voidunion(int p, int q)add connection between p and q booleanconnected(int p, int q)are p and q in the same component? intfind(int p)component identifier for p (0 to N-1) intcount()number of components

10 Read in number of objects N from standard input. Repeat: - read in pair of integers from standard input - write out pair if they are not already connected Dynamic-connectivity client public static void main(String[] args) { int N = StdIn.readInt(); UF uf = new UF(N); while (!StdIn.isEmpty()) { int p = StdIn.readInt(); int q = StdIn.readInt(); if (uf.connected(p, q)) continue; uf.union(p, q); StdOut.println(p + " " + q); } public static void main(String[] args) { int N = StdIn.readInt(); UF uf = new UF(N); while (!StdIn.isEmpty()) { int p = StdIn.readInt(); int q = StdIn.readInt(); if (uf.connected(p, q)) continue; uf.union(p, q); StdOut.println(p + " " + q); } % more tiny.txt % more tiny.txt

11 ‣ dynamic connectivity ‣ quick find ‣ quick union ‣ improvements ‣ applications

12 Data structure. Integer array id[] of size N. Interpretation: p and q in same component iff they have the same id. i id[i] i id[i] and 6 are connected 2, 3, 4, and 9 are connected Quick-find [eager approach]

13 Data structure. Integer array id[] of size N. Interpretation: p and q in same component iff they have the same id. Find. Check if p and q have the same id. i id[i] i id[i] id[3] = 9 ; id[6] = 6 3 and 6 in different components Quick-find [eager approach] 5 and 6 are connected 2, 3, 4, and 9 are connected

14 Data structure. Integer array id[] of size N. Interpretation: p and q in same component iff they have the same id. Find. Check if p and q have the same id. Union. To merge sets containing p and q, change all entries with id[p] to id[q]. i id[i] i id[i] union of 3 and 6 2, 3, 4, 5, 6, and 9 are connected i id[i] i id[i] problem: many values can change Quick-find [eager approach] 5 and 6 are connected 2, 3, 4, and 9 are connected id[3] = 9 ; id[6] = 6 3 and 6 in different components

15 Quick-find example

16 public class QuickFindUF { private int[] id; public QuickFindUF(int N) { id = new int[N]; for (int i = 0; i < N; i++) id[i] = i; } public boolean connected(int p, int q) { return id[p] == id[q]; } public void union(int p, int q) { int pid = id[p]; int qid = id[q]; for (int i = 0; i < id.length; i++) if (id[i] == pid) id[i] = qid; } public class QuickFindUF { private int[] id; public QuickFindUF(int N) { id = new int[N]; for (int i = 0; i < N; i++) id[i] = i; } public boolean connected(int p, int q) { return id[p] == id[q]; } public void union(int p, int q) { int pid = id[p]; int qid = id[q]; for (int i = 0; i < id.length; i++) if (id[i] == pid) id[i] = qid; } change all entries with id[p] to id[q] (linear number of array accesses) set id of each object to itself (N array accesses) Quick-find: Java implementation check whether p and q are in the same component (2 array accesses)

17 Cost model. Number of array accesses (for read or write). Quick-find defect. Union too expensive. Trees are flat, but too expensive to keep them flat. Ex. Takes N 2 array accesses to process sequence of N union commands on N objects. Quick-find is too slow algorithminitunionfind quick-findNN1

18 Rough standard (for now) operations per second words of main memory. Touch all words in approximately 1 second. Ex. Huge problem for quick-find union commands on 10 9 objects. Quick-find takes more than operations. 30+ years of computer time! Paradoxically, quadratic algorithms get worse with newer equipment. New computer may be 10x as fast. But, has 10x as much memory so problem may be 10x bigger. With quadratic algorithm, takes 10x as long! a truism (roughly) since 1950! Quadratic algorithms do not scale

19 ‣ dynamic connectivity ‣ quick find ‣ quick union ‣ improvements ‣ applications

20 Data structure. Integer array id[] of size N. Interpretation: id[i] is parent of i. Root of i is id[id[id[...id[i]...]]]. Quick-union [lazy approach] i id[i] i id[i] p q keep going until it doesn’t change 3's root is 9; 5's root is 6

21 Data structure. Integer array id[] of size N. Interpretation: id[i] is parent of i. Root of i is id[id[id[...id[i]...]]]. Find. Check if p and q have the same root. i id[i] i id[i] Quick-union [lazy approach] keep going until it doesn’t change 's root is 9; 5's root is 6 3 and 5 are in different components p q

22 Data structure. Integer array id[] of size N. Interpretation: id[i] is parent of i. Root of i is id[id[id[...id[i]...]]]. Find. Check if p and q have the same root. Union. To merge sets containing p and q, set the id of p 's root to the id of q 's root i id[i] i id[i] 's root is 9; 5's root is 6 3 and 5 are in different components i id[i] i id[i] only one value changes p q Quick-union [lazy approach] p q keep going until it doesn’t change

23 Quick-union example

24 Quick-union example

25 Quick-union: Java implementation public class QuickUnionUF{ private int[] id; public QuickUnionUF(int N) { id = new int[N]; for (int i = 0; i < N; i++) id[i] = i; } private int root(int i) { while (i != id[i]) i = id[i]; return i; } public boolean connected(int p, int q) { return root(p) == root(q); } public void union(int p, int q) { int i = root(p), j = root(q); id[i] = j; } } public class QuickUnionUF{ private int[] id; public QuickUnionUF(int N) { id = new int[N]; for (int i = 0; i < N; i++) id[i] = i; } private int root(int i) { while (i != id[i]) i = id[i]; return i; } public boolean connected(int p, int q) { return root(p) == root(q); } public void union(int p, int q) { int i = root(p), j = root(q); id[i] = j; } } set id of each object to itself (N array accesses) chase parent pointers until reach root (depth of i array accesses) check if p and q have same root (depth of p and q array accesses) change root of p to point to root of q (depth of p and q array accesses)

26 Cost model. Number of array accesses (for read or write). Quick-find defect. Union too expensive ( N array accesses). Trees are flat, but too expensive to keep them flat. Quick-union defect. Trees can get tall. Find too expensive (could be N array accesses). worst case † includes cost of finding root Quick-union is also too slow algorithminitunionfind quick-findNN1 quick-unionN N † N

27 ‣ dynamic connectivity ‣ quick find ‣ quick union ‣ improvements ‣ applications

28 Weighted quick-union. Modify quick-union to avoid tall trees. Keep track of size of each tree (number of objects). Balance by linking small tree below large one. Improvement 1: weighting

29 Weighted quick-union examples

30 Quick-union and weighted quick-union example

31 Data structure. Same as quick-union, but maintain extra array sz[i] to count number of objects in the tree rooted at i. Find. Identical to quick-union. Union. Modify quick-union to: Merge smaller tree into larger tree. Update the sz[] array. int i = root(p); int j = root(q); if (sz[i] < sz[j]) { id[i] = j; sz[j] += sz[i]; } else { id[j] = i; sz[i] += sz[j]; } int i = root(p); int j = root(q); if (sz[i] < sz[j]) { id[i] = j; sz[j] += sz[i]; } else { id[j] = i; sz[i] += sz[j]; } Weighted quick-union: Java implementation return root(p) == root(q);

32 Running time. Find: takes time proportional to depth of p and q. Union: takes constant time, given roots. Proposition. Depth of any node x is at most lg N. Weighted quick-union analysis 3 x N = 10 depth(x) = 3  lg N

33 Running time. Find: takes time proportional to depth of p and q. Union: takes constant time, given roots. Proposition. Depth of any node x is at most lg N. Pf. When does depth of x increase? Increases by 1 when tree T 1 containing x is merged into another tree T 2. The size of the tree containing x at least doubles since  T 2    T 1 . Size of tree containing x can double at most lg N times. Why? Weighted quick-union analysis T 2 T1T1 T1T1 x

34 Running time. Find: takes time proportional to depth of p and q. Union: takes constant time, given roots. Proposition. Depth of any node x is at most lg N. Q. Stop at guaranteed acceptable performance? A. No, easy to improve further. † includes cost of finding root Weighted quick-union analysis algorithminitunionfind quick-findNN1 quick-unionN N † N weighted QUNlg N † lg N

35 10 Quick union with path compression. Just after computing the root of p, set the id of each examined node to point to that root root(9) Improvement 2: path compression p 10

36 Standard implementation: add second loop to find() to set the id[] of each examined node to the root. Simpler one-pass variant: halve the path length by making every other node in path point to its grandparent. In practice. No reason not to! Keeps tree almost completely flat. only one extra line of code ! public int root(int i) { while (i != id[i]) { id[i] = id[id[i]]; i = id[i]; } return i; } public int root(int i) { while (i != id[i]) { id[i] = id[id[i]]; i = id[i]; } return i; } Path compression: Java implementation

37 Weighted quick-union with path compression example 1 linked to 6 because of path compression 7 linked to 6 because of path compression

38 Proposition. Starting from an empty data structure, any sequence of M union  find operations on N objects makes at most proportional to N + M lg* N array accesses. Proof is very difficult. Can be improved to N + M  ( M, N ). But the algorithm is still simple! Linear-time algorithm for M union-find ops on N objects? Cost within constant factor of reading in the data. In theory, WQUPC is not quite linear. In practice, WQUPC is linear. Amazing fact. No linear-time algorithm exists. see COS 423 Nlg* N Weighted quick-union with path compression: amortized analysis lg* function in "cell-probe" model of computation because lg* N is a constant in this universe Bob Tarjan (Turing Award '86)

39 Bottom line. WQUPC makes it possible to solve problems that could not otherwise be addressed. Ex. [10 9 unions and finds with 10 9 objects] WQUPC reduces time from 30 years to 6 seconds. Supercomputer won't help much; good algorithm enables solution. M union  find operations on a set of N objects algorithmworst-case time quick-findM N quick-unionM N weighted QUN + M log N QU + path compressionN + M log N weighted QU + path compressionN + M lg* N Summary

40 ‣ dynamic connectivity ‣ quick find ‣ quick union ‣ improvements ‣ applications

41 Percolation. Games (Go, Hex). ✓ Dynamic connectivity. Least common ancestor. Equivalence of finite state automata. Hoshen-Kopelman algorithm in physics. Hinley-Milner polymorphic type inference. Kruskal's minimum spanning tree algorithm. Compiling equivalence statements in Fortran. Morphological attribute openings and closings. Matlab's bwlabel() function in image processing. Union-find applications

42 A model for many physical systems: N - by - N grid of sites. Each site is open with probability p (or blocked with probability 1  p ). System percolates iff top and bottom are connected by open sites. Percolation N = 8

43 A model for many physical systems: N - by - N grid of sites. Each site is open with probability p (or blocked with probability 1  p ). System percolates iff top and bottom are connected by open sites. modelsystemvacant siteoccupied sitepercolates electricitymaterialconductorinsulatedconducts fluid flowmaterialemptyblockedporous social interactionpopulationpersonemptycommunicates Percolation

44 Depends on site vacancy probability p. Likelihood of percolation p low (0.4) does not percolate p medium (0.6) percolates? p high (0.8) percolates

45 When N is large, theory guarantees a sharp threshold p *. p  p * : almost certainly percolates. p  p * : almost certainly does not percolate. Q. What is the value of p * ? p* 45 Percolation phase transition N = 100

46 Initialize N - by - N whole grid to be blocked. Declare random sites open until top connected to bottom. Vacancy percentage estimates p *. Monte Carlo simulation N = 20 empty open site (not connected to top) full open site (connected to top) blocked site

47 Q. How to check whether an N -by- N system percolates? Dynamic connectivity solution to estimate percolation threshold open site blocked site N = 5

48 Q. How to check whether an N -by- N system percolates? Create an object for each site and name them 0 to N 2 – 1. Dynamic connectivity solution to estimate percolation threshold open site blocked site N =

49 Q. How to check whether an N -by- N system percolates? Create an object for each site and name them 0 to N 2 – 1. Sites are in same set if connected by open sites. Dynamic connectivity solution to estimate percolation threshold open site blocked site N = 5

50 Q. How to check whether an N -by- N system percolates? Create an object for each site and name them 0 to N 2 – 1. Sites are in same set if connected by open sites. Percolates iff any site on bottom row is connected to site on top row. Dynamic connectivity solution to estimate percolation threshold brute-force algorithm: N 2 calls to connected() open site blocked site N = 5

51 Clever trick. Introduce two virtual sites (and connections to top and bottom). Percolates iff virtual top site is connected to virtual bottom site. Dynamic connectivity solution to estimate percolation threshold virtual top site virtual bottom site efficient algorithm: only 1 call to connected() open site blocked site N = 5

52 Clever trick. Introduce two virtual sites (and connections to top and bottom). Percolates iff virtual top site is connected to virtual bottom site. Open site is full iff connected to virtual top site. Dynamic connectivity solution to estimate percolation threshold empty open site (not connected to top) full open site (connected to top) blocked site N = 5 virtual top site virtual bottom site needed only for visualization

53 Q. How to model as dynamic connectivity problem when opening a new site? Dynamic connectivity solution to estimate percolation threshold open site blocked site N = 5 open this site

54 Q. How to model as dynamic connectivity problem when opening a new site? A. Connect new site to all of its adjacent open sites. Dynamic connectivity solution to estimate percolation threshold open this site open site blocked site N = 5 up to 4 calls to union()

55 Q. What is percolation threshold p * ? A. About for large square lattices. Fast algorithm enables accurate answer to scientific question. constant know only via simulation Percolation threshold p* N = 100

56 Hex. [Piet Hein 1942, John Nash 1948, Parker Brothers 1962] Two players alternate in picking a cell in a hexagonal grid. Black: make a black path from upper left to lower right. White: make a white path from lower left to upper right. Union-find application. Algorithm to detect when a player has won. Hex

57 Steps to developing a usable algorithm. Model the problem. Find an algorithm to solve it. Fast enough? Fits in memory? If not, figure out why. Find a way to address the problem. Iterate until satisfied. The scientific method. Mathematical analysis. Subtext of today’s lecture (and this course)