Algorithms. Algorithms 1.5 UNION-FIND. dynamic connectivity quick find quick union improvements applications ROBERT SEDGEWICK KEVIN WAYNE

Similar documents
Union-Find Algorithms. network connectivity quick find quick union improvements applications

Union-Find Problem. Using Arrays And Chains

4.2 Sorting and Searching

CSE 326, Data Structures. Sample Final Exam. Problem Max Points Score 1 14 (2x7) 2 18 (3x6) Total 92.

The Union-Find Problem Kruskal s algorithm for finding an MST presented us with a problem in data-structure design. As we looked at each edge,

Motivation Suppose we have a database of people We want to gure out who is related to whom Initially, we only have a list of people, and information a

Data Structures Fibonacci Heaps, Amortized Analysis

1.4 Arrays Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright /6/11 12:33 PM!

Data Structures. Jaehyun Park. CS 97SI Stanford University. June 29, 2015

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++


Symbol Tables. Introduction

Binary Search Trees. A Generic Tree. Binary Trees. Nodes in a binary search tree ( B-S-T) are of the form. P parent. Key. Satellite data L R

Binary Heap Algorithms

cs2010: algorithms and data structures

Ordered Lists and Binary Trees

Binary Search Trees. basic implementations randomized BSTs deletion in BSTs

Questions 1 through 25 are worth 2 points each. Choose one best answer for each.

Biostatistics 615/815

dictionary find definition word definition book index find relevant pages term list of page numbers

1.3 Conditionals and Loops

Sources: On the Web: Slides will be available on:

Data Structures and Algorithms

Lecture 3. Linear Programming. 3B1B Optimization Michaelmas 2015 A. Zisserman. Extreme solutions. Simplex method. Interior point method

CS/COE

Efficiency of algorithms. Algorithms. Efficiency of algorithms. Binary search and linear search. Best, worst and average case.

The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!

Binary Trees and Huffman Encoding Binary Search Trees

6. Standard Algorithms

A Static Analyzer for Large Safety-Critical Software. Considered Programs and Semantics. Automatic Program Verification by Abstract Interpretation

CSE 2123 Collections: Sets and Iterators (Hash functions and Trees) Jeremy Morris

Outline BST Operations Worst case Average case Balancing AVL Red-black B-trees. Binary Search Trees. Lecturer: Georgy Gimel farb

Lecture 2 February 12, 2003

Chapter 13: Query Processing. Basic Steps in Query Processing

Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction

Chapter 6: Programming Languages

Efficient representation of integer sets

Computational Mathematics with Python

Binary Search Trees CMPSC 122

Data Structures in Java. Session 15 Instructor: Bert Huang

6.080/6.089 GITCS Feb 12, Lecture 3

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

Analysis of Micromouse Maze Solving Algorithms

Testing LTL Formula Translation into Büchi Automata

Computational Mathematics with Python

S. Muthusundari. Research Scholar, Dept of CSE, Sathyabama University Chennai, India Dr. R. M.

Guessing Game: NP-Complete?

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

AP Computer Science Java Mr. Clausen Program 9A, 9B

Introduction to Programming System Design. CSCI 455x (4 Units)

Analysis of a Search Algorithm

1.204 Lecture 10. Greedy algorithms: Job scheduling. Greedy method

Parallelization: Binary Tree Traversal

Stacks. Data Structures and Data Types. Collections

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

Faster deterministic integer factorisation

Algorithms. Algorithms GEOMETRIC APPLICATIONS OF BSTS. 1d range search line segment intersection kd trees interval search trees rectangle intersection

Matrix Multiplication

Fast Sequential Summation Algorithms Using Augmented Data Structures

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

Why Use Binary Trees?

Hash Tables. Computer Science E-119 Harvard Extension School Fall 2012 David G. Sullivan, Ph.D. Data Dictionary Revisited

Vector storage and access; algorithms in GIS. This is lecture 6

Data Structures and Data Manipulation

Minimum Spanning Trees

recursion, O(n), linked lists 6/14

A Comparison of Dictionary Implementations

B-Trees. Algorithms and data structures for external memory as opposed to the main memory B-Trees. B -trees

Sample Questions Csci 1112 A. Bellaachia

22S:295 Seminar in Applied Statistics High Performance Computing in Statistics

APP INVENTOR. Test Review

In mathematics, it is often important to get a handle on the error term of an approximation. For instance, people will write

Spring 2011 Prof. Hyesoon Kim

CHM 579 Lab 1: Basic Monte Carlo Algorithm

Cpt S 223. School of EECS, WSU

Components: Interconnect Page 1 of 18

Universal hashing. In other words, the probability of a collision for two different keys x and y given a hash function randomly chosen from H is 1/m.

Overview. Lecture 1: an introduction to CUDA. Hardware view. Hardware view. hardware view software view CUDA programming

The Model Checker SPIN

4.5 Symbol Table Applications

5.1 Bipartite Matching

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

Persistent Data Structures

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

Regular Expressions and Automata using Haskell

Common Data Structures

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Previous Lectures. B-Trees. External storage. Two types of memory. B-trees. Main principles

Binary Search Trees. Data in each node. Larger than the data in its left child Smaller than the data in its right child

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

A binary heap is a complete binary tree, where each node has a higher priority than its children. This is called heap-order property

Data storage Tree indexes

6 March Array Implementation of Binary Trees

Sorting revisited. Build the binary search tree: O(n^2) Traverse the binary tree: O(n) Total: O(n^2) + O(n) = O(n^2)

6.852: Distributed Algorithms Fall, Class 2

CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis. Linda Shapiro Winter 2015

Sequential Data Structures

APPM4720/5720: Fast algorithms for big data. Gunnar Martinsson The University of Colorado at Boulder

CPLEX Tutorial Handout

Transcription:

Algorithms ROBERT SEDGEWICK KEVIN WAYNE 1.5 UNION-FIND Algorithms F O U R T H E D I T I O N ROBERT SEDGEWICK KEVIN WAYNE dynamic connectivity quick find quick union improvements applications http://algs4.cs.princeton.edu

Subtext of today s lecture (and this course) 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 not. Find a way to address the problem. Iterate until satisfied. The scientific method. Mathematical analysis. 2

1.5 UNION-FIND Algorithms ROBERT SEDGEWICK KEVIN WAYNE dynamic connectivity quick find quick union improvements applications http://algs4.cs.princeton.edu

Dynamic connectivity problem Given a set of N objects, support two operation: Connect two objects. Is there a path connecting the two objects? connect 4 and 3 connect 3 and 8 connect 6 and 5 connect 9 and 4 connect 2 and 1 are 0 and 7 connected? are 8 and 9 connected? connect 5 and 0 connect 7 and 2 connect 6 and 1 connect 1 and 0 are 0 and 7 connected? 0 1 2 3 4 5 6 7 8 9 4

A larger connectivity example Q. Is there a path connecting p and q? p q A. Yes. 5

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

Modeling the connections 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 component. Maximal set of objects that are mutually connected. 0 1 2 3 4 5 6 7 { 0 } { 1 4 5 } { 2 3 6 7 } 3 connected components 7

Implementing the operations Find. In which component is object p? Connected. Are objects p and q in the same component? Union. Replace components containing objects p and q with their union. 0 1 2 3 union(2, 5) 0 1 2 3 4 5 6 7 4 5 6 7 { 0 } { 1 4 5 } { 2 3 6 7 } { 0 } { 1 2 3 4 5 6 7 } 3 connected components 2 connected components 8

Union-find data type (API) Goal. Design efficient data structure for union-find. Number of objects N can be huge. Number of operations M can be huge. Union and find operations may be intermixed. public class UF UF(int N) initialize union-find data structure with N singleton objects (0 to N 1) void union(int p, int q) add connection between p and q int find(int p) component identifier for p (0 to N 1) boolean connected(int p, int q) are p and q in the same component? public boolean connected(int p, int q) { return find(p) == find(q); } 1-line implementation of connected() 9

Dynamic-connectivity client Read in number of objects N from standard input. Repeat: read in pair of integers from standard input if they are not yet connected, connect them and print out pair 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)) { uf.union(p, q); StdOut.println(p + " " + q); } } } % more tinyuf.txt 10 4 3 3 8 6 5 9 4 2 1 8 9 5 0 7 2 6 1 1 0 6 7 already connected 10

1.5 UNION-FIND Algorithms ROBERT SEDGEWICK KEVIN WAYNE dynamic connectivity quick find quick union improvements applications http://algs4.cs.princeton.edu

Quick-find [eager approach] Data structure. if and only if Integer array id[] of length N. Interpretation: id[p] is the id of the component containing p. id[] 0 1 0 1 2 3 1 8 4 5 8 0 6 7 0 1 8 9 8 8 0, 5 and 6 are connected 1, 2, and 7 are connected 3, 4, 8, and 9 are connected 0 1 2 3 4 5 6 7 8 9 12

Quick-find [eager approach] Data structure. Integer array id[] of length N. Interpretation: id[p] is the id of the component containing p. 0 1 2 3 4 5 6 7 8 9 id[] 0 1 1 8 8 0 0 1 8 8 Find. What is the id of p? Connected. Do p and q have the same id? id[6] = 0; id[1] = 1 6 and 1 are not connected Union. To merge components containing p and q, change all entries whose id equals id[p] to id[q]. 0 1 2 3 4 5 6 7 8 9 id[] 1 1 1 8 8 1 1 1 8 8 after union of 6 and 1 problem: many values can change 13

Quick-find demo 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 id[] 0 1 2 3 4 5 6 7 8 9 14

Quick-find demo 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 id[] 1 1 1 8 8 1 1 1 8 8

Quick-find: Java implementation public class QuickFindUF { private int[] id; public QuickFindUF(int N) { } id = new int[n]; for (int i = 0; i < N; i++) id[i] = i; set id of each object to itself (N array accesses) public int find(int p) { return id[p]; } return the id of p (1 array access) } 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] (at most 2N + 2 array accesses) 16

Quick-find is too slow Cost model. Number of array accesses (for read or write). algorithm initialize union find connected quick-find N N 1 1 order of growth of number of array accesses quadratic Union is too expensive. It takes N 2 array accesses to process a sequence of N union operations on N objects. 17

Quadratic algorithms do not scale Rough standard (for now). 109 operations per second. a truism (roughly) since 1950! 109 words of main memory. Touch all words in approximately 1 second. Ex. Huge problem for quick-find. 109 union commands on 10 9 objects. Quick-find takes more than 1018 operations. 30+ years of computer time! Quadratic algorithms don't scale with technology. New computer may be 10x as fast. But, has 10x as much memory want to solve a problem that is 10x as big. With quadratic algorithm, takes 10x as long! time 64T 32T 16T 8T quadratic linearithmic linear size 1K 2K 4K 8K 18

1.5 UNION-FIND Algorithms ROBERT SEDGEWICK KEVIN WAYNE dynamic connectivity quick find quick union improvements applications http://algs4.cs.princeton.edu

Quick-union [lazy approach] Data structure. Integer array id[] of length N. Interpretation: id[i] is parent of i. Root of i is id[id[id[...id[i]...]]]. keep going until it doesn t change (algorithm ensures no cycles) 0 1 9 6 7 8 0 1 2 3 4 5 6 7 8 9 id[] 0 1 9 4 9 6 6 7 8 9 2 4 5 3 parent of 3 is 4 root of 3 is 9 20

Quick-union [lazy approach] Data structure. Integer array id[] of length N. Interpretation: id[i] is parent of i. Root of i is id[id[id[...id[i]...]]]. 0 1 9 6 7 8 0 1 2 3 4 5 6 7 8 9 id[] 0 1 9 4 9 6 6 7 8 9 2 4 5 q p 3 Find. What is the root of p? Connected. Do p and q have the same root? root of 3 is 9 root of 5 is 6 3 and 5 are not connected Union. To merge components containing p and q, 0 1 6 7 8 set the id of p's root to the id of q's root. 9 0 1 2 3 4 5 6 7 8 9 5 q id[] 0 1 9 4 9 6 6 7 8 6 2 4 only one value changes p 3 21

Quick-union demo 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 id[] 0 1 2 3 4 5 6 7 8 9 22

Quick-union demo 8 1 3 9 0 2 7 4 5 0 1 2 3 4 5 6 7 8 9 6 id[] 1 8 1 8 3 0 5 1 8 8

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; } set id of each object to itself (N array accesses) public int find(int i) { while (i!= id[i]) i = id[i]; return i; } chase parent pointers until reach root (depth of i array accesses) } public void union(int p, int q) { int i = find(p); int j = find(q); id[i] = j; } change root of p to point to root of q (depth of p and q array accesses) 24

Quick-union is also too slow Cost model. Number of array accesses (for read or write). algorithm initialize union find connected quick-find N N 1 1 quick-union N N N N worst case includes cost of finding roots 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/connected too expensive (could be N array accesses). 25

1.5 UNION-FIND Algorithms ROBERT SEDGEWICK KEVIN WAYNE dynamic connectivity quick find quick union improvements applications http://algs4.cs.princeton.edu

Improvement 1: weighting Weighted quick-union. Modify quick-union to avoid tall trees. Keep track of size of each tree (number of objects). Balance by linking root of smaller tree to root of larger tree. p p q quick-union q reasonable alternatives: union by height or "rank" p smaller tree larger tree might put the larger tree lower smaller tree larger tree weighted p always chooses the better alternative q q larger tree smaller tree smaller tree larger tree 27

Weighted quick-union demo 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 id[] 0 1 2 3 4 5 6 7 8 9 28

Weighted quick-union demo 6 4 0 2 5 3 8 9 1 7 0 1 2 3 4 5 6 7 8 9 id[] 6 2 6 4 6 6 6 2 4 4

Quick-union and weighted quick-union example quick-union weighted average distance to root: 5.11 weighted average distance to root: 1.52 Quick-union and weighted quick-union (100 sites, 88 union() operations) 30

Weighted quick-union: Java implementation Data structure. Same as quick-union, but maintain extra array sz[i] to count number of objects in the tree rooted at i. Find/connected. Identical to quick-union. Union. Modify quick-union to: Link root of smaller tree to root of larger tree. Update the sz[] array. int i = find(p); int 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]; } 31

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

Weighted quick-union analysis Running time. Find: takes time proportional to depth of p. Union: takes constant time, given roots. lg = base-2 logarithm Proposition. Depth of any node x is at most lg N. Pf. What causes the depth of object x to increase? Increases by 1 when tree T1 containing x is merged into another tree T2. 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? 1 2 4 T2 T1 x 8 16 N lg N 33

Weighted quick-union analysis Running time. Find: takes time proportional to depth of p. Union: takes constant time, given roots. Proposition. Depth of any node x is at most lg N. algorithm initialize union find connected quick-find N N 1 1 quick-union N N N N weighted QU N lg N lg N lg N includes cost of finding roots Q. Stop at guaranteed acceptable performance? A. No, easy to improve further. 34

Improvement 2: path compression Quick union with path compression. Just after computing the root of p, set the id[] of each examined node to point to that root. 0 root 1 2 3 4 5 6 7 8 x 9 p 10 11 12 35

Improvement 2: path compression Quick union with path compression. Just after computing the root of p, set the id[] of each examined node to point to that root. 0 root p 9 1 2 11 12 3 4 5 x 6 7 8 10 36

Improvement 2: path compression Quick union with path compression. Just after computing the root of p, set the id[] of each examined node to point to that root. 0 root p 9 6 1 2 11 12 8 x 3 4 5 10 7 37

Improvement 2: path compression Quick union with path compression. Just after computing the root of p, set the id[] of each examined node to point to that root. 0 root p 9 6 3 1 2 x 11 12 8 7 4 5 10 38

Improvement 2: path compression Quick union with path compression. Just after computing the root of p, set the id[] of each examined node to point to that root. x 0 root p 9 6 3 1 2 11 12 8 7 4 5 10 Bottom line. Now, find() has the side effect of compressing the tree. 39

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

Weighted quick-union with path compression: amortized analysis Proposition. [Hopcroft-Ulman, Tarjan] Starting from an empty data structure, any sequence of M union-find ops on N objects makes c ( N + M lg* N ) array accesses. Analysis can be improved to N + M α(m, N). Simple algorithm with fascinating mathematics. N lg* N 1 0 2 1 4 2 16 3 65536 4 2 65536 5 Linear-time algorithm for M union-find ops on N objects? iterated lg function Cost within constant factor of reading in the data. In theory, WQUPC is not quite linear. In practice, WQUPC is linear. Amazing fact. [Fredman-Saks] No linear-time algorithm exists. in "cell-probe" model of computation 41

Summary Key point. Weighted quick union (and/or path compression) makes it possible to solve problems that could not otherwise be addressed. algorithm quick-find quick-union weighted QU QU + path compression weighted QU + path compression worst-case time M N M N N + M log N N + M log N N + M lg* N order of growth for M union-find operations on a set of N objects 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. 42

1.5 UNION-FIND Algorithms ROBERT SEDGEWICK KEVIN WAYNE dynamic connectivity quick find quick union improvements applications http://algs4.cs.princeton.edu

Union-find applications 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. 44

Percolation An abstract model for many physical systems: N-by-N grid of sites. Each site is open with probability p (and blocked with probability 1 p). System percolates iff top and bottom are connected by open sites. percolates blocked site does not percolate N = 8 open site open site connected to top no open site connected to top 45

Percolation An abstract model for many physical systems: N-by-N grid of sites. Each site is open with probability p (and blocked with probability 1 p). System percolates iff top and bottom are connected by open sites. model system vacant site occupied site percolates electricity material conductor insulated conducts fluid flow material empty blocked porous social interaction population person empty communicates 46

Likelihood of percolation Depends on grid size N and site vacancy probability p. p low (0.4) does not percolate p medium (0.6) percolates? p high (0.8) percolates 47

Percolation phase transition 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*? 1 percolation probability N = 100 0 p* 0 0.593 1 site vacancy probability p 48

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

Dynamic connectivity solution to estimate percolation threshold Q. How to check whether an N-by-N system percolates? A. Model as a dynamic connectivity problem and use union-find. N = 5 open site blocked site 50

Dynamic connectivity solution to estimate percolation threshold 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. N = 5 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 open site blocked site 51

Dynamic connectivity solution to estimate percolation threshold 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 component iff connected by open sites. N = 5 open site blocked site 52

Dynamic connectivity solution to estimate percolation threshold 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 component iff connected by open sites. Percolates iff any site on bottom row is connected to any site on top row. brute-force algorithm: N 2 calls to connected() N = 5 top row bottom row open site blocked site 53

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

Dynamic connectivity solution to estimate percolation threshold Q. How to model opening a new site? open this site N = 5 open site blocked site 55

Dynamic connectivity solution to estimate percolation threshold Q. How to model opening a new site? A. Mark new site as open; connect it to all of its adjacent open sites. up to 4 calls to union() open this site N = 5 open site blocked site 56

Percolation threshold Q. What is percolation threshold p*? A. About 0.592746 for large square lattices. constant known only via simulation 1 percolation probability N = 100 0 p* 0 0.593 1 site vacancy probability p Fast algorithm enables accurate answer to scientific question. 57

Subtext of today s lecture (and this course) 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. 58