SlideShare una empresa de Scribd logo
1 de 64
Descargar para leer sin conexión
ROBERT SEDGEWICK | KEVIN WAYNE
F O U R T H E D I T I O N
Algorithms
http://algs4.cs.princeton.edu
Algorithms ROBERT SEDGEWICK | KEVIN WAYNE
‣ dynamic connectivity
‣ quick find
‣ quick union
‣ improvements
‣ applications
1.5 UNION-FIND
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.
2
Subtext of today’s lecture (and this course)
http://algs4.cs.princeton.edu
ROBERT SEDGEWICK | KEVIN WAYNE
Algorithms
‣ dynamic connectivity
‣ quick find
‣ quick union
‣ improvements
‣ applications
1.5 UNION-FIND
Given a set of N objects.
・Union command: connect two objects.
・Find/connected query: is there a path connecting the two objects?
4
Dynamic connectivity
union(4, 3)
union(3, 8)
union(6, 5)
union(9, 4)
union(2, 1)
connected(0, 7)
connected(8, 9)
union(5, 0)
union(7, 2)
connected(0, 7)
union(1, 0)
union(6, 1)
0 1 2 3 4
5 6 7 8 9
𐄂
✔
✔
Q. Is there a path connecting p and q ?
A. Yes.
5
Connectivity example
p
q
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 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.
6
Modeling the objects
can use symbol table to translate from site
names to integers: stay tuned (Chapter 3)
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.
7
Modeling the connections
{ 0 } { 1 4 5 } { 2 3 6 7 }
3 connected components
0 1 2 3
4 5 6 7
Find query. Check if two objects are in the same component.
Union command. Replace components containing two objects
with their union.
8
Implementing the operations
{ 0 } { 1 4 5 } { 2 3 6 7 }
3 connected components
0 1 2 3
4 5 6 7
union(2, 5)
{ 0 } { 1 2 3 4 5 6 7 }
2 connected components
0 1 2 3
4 5 6 7
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 UFpublic class UFpublic class UF
UF(int N)
initialize union-find data structure with
N objects (0 to N – 1)
void union(int p, int q) add connection between p and q
boolean connected(int p, int q) are p and q in the same component?
int find(int p) component identifier for p (0 to N – 1)
int count() number of components
10
・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
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))
{
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
http://algs4.cs.princeton.edu
ROBERT SEDGEWICK | KEVIN WAYNE
Algorithms
‣ dynamic connectivity
‣ quick find
‣ quick union
‣ improvements
‣ applications
1.5 UNION-FIND
http://algs4.cs.princeton.edu
ROBERT SEDGEWICK | KEVIN WAYNE
Algorithms
‣ dynamic connectivity
‣ quick find
‣ quick union
‣ improvements
‣ applications
1.5 UNION-FIND
13
Data structure.
・Integer array id[] of length N.
・Interpretation: p and q are connected iff they have the same id.
0, 5 and 6 are connected
1, 2, and 7 are connected
3, 4, 8, and 9 are connected
Quick-find [eager approach]
0 1 2 3 4
5 6 7 8 9
0 1
0 1
1 8
2 3
8 0
4 5
0 1
6 7
8 8
8 9
id[]
if and only if
14
Data structure.
・Integer array id[] of length N.
・Interpretation: p and q are connected iff they have the same id.
Find. Check if p and q have the same id.
Union. To merge components containing p and q, change all entries
whose id equals id[p] to id[q].
after union of 6 and 1
problem: many values can change
Quick-find [eager approach]
id[6] = 0; id[1] = 1
6 and 1 are not connected
0 1
0 1
1 8
2 3
8 0
4 5
0 1
6 7
8 8
8 9
1 1
0 1
1 8
2 3
8 1
4 5
1 1
6 7
8 8
8 9
id[]
id[]
15
Quick-find demo
0 1 2 3 4
5 6 7 8 9
0 1
0 1
2 3
2 3
4 5
4 5
6 7
6 7
8 9
8 9
id[]
Quick-find demo
0 1 2 3 4
5 6 7 8 9
1 1
0 1
1 8
2 3
8 1
4 5
1 1
6 7
8 8
8 9
id[]
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;
}
}
17
Quick-find: Java implementation
set id of each object to itself
(N array accesses)
change all entries with id[p] to id[q]
(at most 2N + 2 array accesses)
check whether p and q
are in the same component
(2 array accesses)
Cost model. Number of array accesses (for read or write).
Union is too expensive. It takes N 2 array accesses to process a sequence of
N union commands on N objects.
18
Quick-find is too slow
algorithm initialize union find
quick-find N N 1
order of growth of number of array accesses
quadratic
Rough standard (for now).
・109 operations per second.
・109 words of main memory.
・Touch all words in approximately 1 second.
Ex. Huge problem for quick-find.
・109 union commands on 109 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!
19
a truism (roughly)
since 1950!
Quadratic algorithms do not scale
8T
16T
32T
64T
time
1K 2K 4K 8Ksize
quadratic
linearithmic
linear
http://algs4.cs.princeton.edu
ROBERT SEDGEWICK | KEVIN WAYNE
Algorithms
‣ dynamic connectivity
‣ quick find
‣ quick union
‣ improvements
‣ applications
1.5 UNION-FIND
http://algs4.cs.princeton.edu
ROBERT SEDGEWICK | KEVIN WAYNE
Algorithms
‣ dynamic connectivity
‣ quick find
‣ quick union
‣ improvements
‣ applications
1.5 UNION-FIND
Data structure.
・Integer array id[] of length N.
・Interpretation: id[i] is parent of i.
・Root of i is id[id[id[...id[i]...]]].
22
root of 3 is 9
Quick-union [lazy approach]
keep going until it doesn’t change
(algorithm ensures no cycles)
0 1
0 1
9 4
2 3
9 6
4 5
6 7
6 7
8 9
8 9
id[]
3
54
70 1 9 6 8
2
Data structure.
・Integer array id[] of length 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 components containing p and q,
set the id of p's root to the id of q's root.
23
Quick-union [lazy approach]
0 1
0 1
9 4
2 3
9 6
4 5
6 7
6 7
8 9
8 9
id[]
3
4
70 1
9
6 8
2
only one value changes
p
q
0 1
0 1
9 4
2 3
9 6
4 5
6 7
6 7
8 6
8 9
id[]
5
3
54
70 1 9 6 8
2
p
q
root of 3 is 9
root of 5 is 6
3 and 5 are not connected
24
Quick-union demo
0 1 2 3 4 5 6 7 8 9
0 1
0 1
2 3
2 3
4 5
4 5
6 7
6 7
8 9
8 9
id[]
Quick-union demo
0
1
2
5
6
7
3
4
8
9
1 8
0 1
1 8
2 3
3 0
4 5
5 1
6 7
8 8
8 9
id[]
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);
int 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
27
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 roots
Quick-union is also too slow
algorithm initialize union find
quick-find N N 1
quick-union N N † N
http://algs4.cs.princeton.edu
ROBERT SEDGEWICK | KEVIN WAYNE
Algorithms
‣ dynamic connectivity
‣ quick find
‣ quick union
‣ improvements
‣ applications
1.5 UNION-FIND
http://algs4.cs.princeton.edu
ROBERT SEDGEWICK | KEVIN WAYNE
Algorithms
‣ dynamic connectivity
‣ quick find
‣ quick union
‣ improvements
‣ applications
1.5 UNION-FIND
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.
30
Improvement 1: weighting
smaller
tree
larger
tree
q
p
smaller
tree
larger
tree
q
p
smaller
tree
larger
tree
q
p
smaller
tree
larger
tree
q
p
Weighted quick-union
weighted
quick-union
always chooses the
better alternative
might put the
larger tree lower
reasonable alternatives:
union by height or "rank"
31
Weighted quick-union demo
0 1 2 3 4 5 6 7 8 9
0 1
0 1
2 3
2 3
4 5
4 5
6 7
6 7
8 9
8 9
id[]
Weighted quick-union demo
98
4
3 71
2 50
6
6 2
0 1
6 4
2 3
6 6
4 5
6 2
6 7
4 4
8 9
id[]
33
Quick-union and weighted quick-union example
Quick-union and weighted quick-union (100 sites, 88 union() operations)
weighted
quick-union
average distance to root: 1.52
average distance to root: 5.11
34
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:
・Link root of smaller tree to root of larger tree.
・Update the sz[] array.
int i = root(p);
int j = root(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]; }
Weighted quick-union: Java implementation
return root(p) == root(q);
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.
35
Weighted quick-union analysis
lg = base-2 logarithm
x
N = 10
depth(x) = 3 ≤ lg N
36
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 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?
Weighted quick-union analysis
T2
T1
x
37
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 roots
Weighted quick-union analysis
algorithm initialize union connected
quick-find N N 1
quick-union N N † N
weighted QU N lg N † lg N
Quick union with path compression. Just after computing the root of p,
set the id of each examined node to point to that root.
38
Improvement 2: path compression
1211
9
10
8
6 7
3
x
2
54
0
1
root
p
Quick union with path compression. Just after computing the root of p,
set the id of each examined node to point to that root.
39
Improvement 2: path compression
10
8
6 7
31211
9 2
54
0
1
root
x
p
Quick union with path compression. Just after computing the root of p,
set the id of each examined node to point to that root.
40
Improvement 2: path compression
7
3
10
8
6
1211
9 2
54
0
1
root
x
p
Quick union with path compression. Just after computing the root of p,
set the id of each examined node to point to that root.
41
Improvement 2: path compression
10
8
6 2
54
0
1
7
3
root
x
p
1211
9
Quick union with path compression. Just after computing the root of p,
set the id of each examined node to point to that root.
42
Improvement 2: path compression
10
8
6
7
3
x
root
2
54
0
1
p
1211
9
Two-pass implementation: add second loop to root() to set the id[]
of each examined node to the root.
Simpler one-pass variant: Make every other node in path point to its
grandparent (thereby halving path length).
In practice. No reason not to! Keeps tree almost completely flat.
43
Path compression: Java implementation
only one extra line of code !
private int root(int i)
{
while (i != id[i])
{
id[i] = id[id[i]];
i = id[i];
}
return i;
}
44
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.
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. [Fredman-Saks] No linear-time algorithm exists.
N lg* N
1 0
2 1
4 2
16 3
65536 4
265536 5
Weighted quick-union with path compression: amortized analysis
iterate log function
in "cell-probe" model of computation
Bottom line. Weighted quick union (with path compression) makes it
possible to solve problems that could not otherwise be addressed.
Ex. [109 unions and finds with 109 objects]
・WQUPC reduces time from 30 years to 6 seconds.
・Supercomputer won't help much; good algorithm enables solution.
45
M union-find operations on a set of N objects
algorithm worst-case time
quick-find M N
quick-union M N
weighted QU N + M log N
QU + path compression N + M log N
weighted QU + path compression N + M lg* N
Summary
http://algs4.cs.princeton.edu
ROBERT SEDGEWICK | KEVIN WAYNE
Algorithms
‣ dynamic connectivity
‣ quick find
‣ quick union
‣ improvements
‣ applications
1.5 UNION-FIND
http://algs4.cs.princeton.edu
ROBERT SEDGEWICK | KEVIN WAYNE
Algorithms
‣ dynamic connectivity
‣ quick find
‣ quick union
‣ improvements
‣ applications
1.5 UNION-FIND
48
・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
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.
49
Percolation
N = 8
does not percolatepercolates
open site connected to top
blocked
site
open
site
no open site connected to top
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.
50
model system vacant site occupied site percolates
electricity material conductor insulated conducts
fluid flow material empty blocked porous
social interaction population person empty communicates
Percolation
Depends on site vacancy probability p.
51
Likelihood of percolation
p low (0.4)
does not percolate
p medium (0.6)
percolates?
p high (0.8)
percolates
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* ?
52
Percolation phase transition
0.5930
0
1
1
site vacancy probability p
percolation
probability
p*
N = 100
・Initialize N-by-N whole grid to be blocked.
・Declare random sites open until top connected to bottom.
・Vacancy percentage estimates p*.
53
Monte Carlo simulation
N = 20
empty open site
(not connected to top)
full open site
(connected to top)
blocked site
54
Q. How to check whether an N-by-N system percolates?
Dynamic connectivity solution to estimate percolation threshold
open site
blocked site
N = 5
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.
55
Dynamic connectivity solution to estimate percolation threshold
open site
blocked site
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
56
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 if connected by open sites.
Dynamic connectivity solution to estimate percolation threshold
open site
blocked site
N = 5
57
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 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 top row
bottom row
Clever trick. Introduce 2 virtual sites (and connections to top and bottom).
・Percolates iff virtual top site is connected to virtual bottom site.
58
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 top row
bottom row
Q. How to model opening a new site?
59
Dynamic connectivity solution to estimate percolation threshold
open site
blocked site
N = 5
open this site
Q. How to model opening a new site?
A. Mark new site as open; connect it to all of its adjacent open sites.
60
Dynamic connectivity solution to estimate percolation threshold
open this site
open site
blocked site
N = 5
up to 4 calls to union()
61
Q. What is percolation threshold p* ?
A. About 0.592746 for large square lattices.
Fast algorithm enables accurate answer to scientific question.
constant known only via simulation
Percolation threshold
0.5930
0
1
1
site vacancy probability p
percolation
probability
p*
N = 100
http://algs4.cs.princeton.edu
ROBERT SEDGEWICK | KEVIN WAYNE
Algorithms
‣ dynamic connectivity
‣ quick find
‣ quick union
‣ improvements
‣ applications
1.5 UNION-FIND
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.
63
Subtext of today’s lecture (and this course)
ROBERT SEDGEWICK | KEVIN WAYNE
F O U R T H E D I T I O N
Algorithms
http://algs4.cs.princeton.edu
Algorithms ROBERT SEDGEWICK | KEVIN WAYNE
‣ dynamic connectivity
‣ quick find
‣ quick union
‣ improvements
‣ applications
1.5 UNION-FIND

Más contenido relacionado

La actualidad más candente

Recurrent Neuronal Network tailored for Weather Radar Nowcasting
Recurrent Neuronal Network tailored for Weather Radar NowcastingRecurrent Neuronal Network tailored for Weather Radar Nowcasting
Recurrent Neuronal Network tailored for Weather Radar NowcastingAndreas Scheidegger
 
Heapsortokkay
HeapsortokkayHeapsortokkay
HeapsortokkayRemesha
 
Array ADT(Abstract Data Type)|Data Structure
Array ADT(Abstract Data Type)|Data StructureArray ADT(Abstract Data Type)|Data Structure
Array ADT(Abstract Data Type)|Data StructureAkash Gaur
 
Chapter 8 advanced sorting and hashing for print
Chapter 8 advanced sorting and hashing for printChapter 8 advanced sorting and hashing for print
Chapter 8 advanced sorting and hashing for printAbdii Rashid
 
High-Performance Graph Analysis and Modeling
High-Performance Graph Analysis and ModelingHigh-Performance Graph Analysis and Modeling
High-Performance Graph Analysis and ModelingNesreen K. Ahmed
 
GraphX and Pregel - Apache Spark
GraphX and Pregel - Apache SparkGraphX and Pregel - Apache Spark
GraphX and Pregel - Apache SparkAshutosh Trivedi
 
딥러닝 중급 - AlexNet과 VggNet (Basic of DCNN : AlexNet and VggNet)
딥러닝 중급 - AlexNet과 VggNet (Basic of DCNN : AlexNet and VggNet)딥러닝 중급 - AlexNet과 VggNet (Basic of DCNN : AlexNet and VggNet)
딥러닝 중급 - AlexNet과 VggNet (Basic of DCNN : AlexNet and VggNet)Hansol Kang
 
Introduction into R for historians (part 1: introduction)
Introduction into R for historians (part 1: introduction)Introduction into R for historians (part 1: introduction)
Introduction into R for historians (part 1: introduction)Richard Zijdeman
 
LeetCode Solutions In Java .pdf
LeetCode Solutions In Java .pdfLeetCode Solutions In Java .pdf
LeetCode Solutions In Java .pdfzupsezekno
 
Quicksort with Equal Keys
Quicksort with Equal KeysQuicksort with Equal Keys
Quicksort with Equal KeysSebastian Wild
 
廣宣學堂: R programming for_quantitative_finance_0623
廣宣學堂: R programming for_quantitative_finance_0623 廣宣學堂: R programming for_quantitative_finance_0623
廣宣學堂: R programming for_quantitative_finance_0623 Paul Chao
 
LarKC Tutorial at ISWC 2009 - Data Model
LarKC Tutorial at ISWC 2009 - Data ModelLarKC Tutorial at ISWC 2009 - Data Model
LarKC Tutorial at ISWC 2009 - Data ModelLarKC
 
Uwe Friedrichsen – Extreme availability and self-healing data with CRDTs - No...
Uwe Friedrichsen – Extreme availability and self-healing data with CRDTs - No...Uwe Friedrichsen – Extreme availability and self-healing data with CRDTs - No...
Uwe Friedrichsen – Extreme availability and self-healing data with CRDTs - No...NoSQLmatters
 
Pi j3.4 data-structures
Pi j3.4 data-structuresPi j3.4 data-structures
Pi j3.4 data-structuresmcollison
 
LSGAN - SIMPle(Simple Idea Meaningful Performance Level up)
LSGAN - SIMPle(Simple Idea Meaningful Performance Level up)LSGAN - SIMPle(Simple Idea Meaningful Performance Level up)
LSGAN - SIMPle(Simple Idea Meaningful Performance Level up)Hansol Kang
 
A Tale of Two Graph Frameworks on Spark: GraphFrames and Tinkerpop OLAP Artem...
A Tale of Two Graph Frameworks on Spark: GraphFrames and Tinkerpop OLAP Artem...A Tale of Two Graph Frameworks on Spark: GraphFrames and Tinkerpop OLAP Artem...
A Tale of Two Graph Frameworks on Spark: GraphFrames and Tinkerpop OLAP Artem...Spark Summit
 

La actualidad más candente (17)

Recurrent Neuronal Network tailored for Weather Radar Nowcasting
Recurrent Neuronal Network tailored for Weather Radar NowcastingRecurrent Neuronal Network tailored for Weather Radar Nowcasting
Recurrent Neuronal Network tailored for Weather Radar Nowcasting
 
Heapsortokkay
HeapsortokkayHeapsortokkay
Heapsortokkay
 
Realtime Analytics
Realtime AnalyticsRealtime Analytics
Realtime Analytics
 
Array ADT(Abstract Data Type)|Data Structure
Array ADT(Abstract Data Type)|Data StructureArray ADT(Abstract Data Type)|Data Structure
Array ADT(Abstract Data Type)|Data Structure
 
Chapter 8 advanced sorting and hashing for print
Chapter 8 advanced sorting and hashing for printChapter 8 advanced sorting and hashing for print
Chapter 8 advanced sorting and hashing for print
 
High-Performance Graph Analysis and Modeling
High-Performance Graph Analysis and ModelingHigh-Performance Graph Analysis and Modeling
High-Performance Graph Analysis and Modeling
 
GraphX and Pregel - Apache Spark
GraphX and Pregel - Apache SparkGraphX and Pregel - Apache Spark
GraphX and Pregel - Apache Spark
 
딥러닝 중급 - AlexNet과 VggNet (Basic of DCNN : AlexNet and VggNet)
딥러닝 중급 - AlexNet과 VggNet (Basic of DCNN : AlexNet and VggNet)딥러닝 중급 - AlexNet과 VggNet (Basic of DCNN : AlexNet and VggNet)
딥러닝 중급 - AlexNet과 VggNet (Basic of DCNN : AlexNet and VggNet)
 
Introduction into R for historians (part 1: introduction)
Introduction into R for historians (part 1: introduction)Introduction into R for historians (part 1: introduction)
Introduction into R for historians (part 1: introduction)
 
LeetCode Solutions In Java .pdf
LeetCode Solutions In Java .pdfLeetCode Solutions In Java .pdf
LeetCode Solutions In Java .pdf
 
Quicksort with Equal Keys
Quicksort with Equal KeysQuicksort with Equal Keys
Quicksort with Equal Keys
 
廣宣學堂: R programming for_quantitative_finance_0623
廣宣學堂: R programming for_quantitative_finance_0623 廣宣學堂: R programming for_quantitative_finance_0623
廣宣學堂: R programming for_quantitative_finance_0623
 
LarKC Tutorial at ISWC 2009 - Data Model
LarKC Tutorial at ISWC 2009 - Data ModelLarKC Tutorial at ISWC 2009 - Data Model
LarKC Tutorial at ISWC 2009 - Data Model
 
Uwe Friedrichsen – Extreme availability and self-healing data with CRDTs - No...
Uwe Friedrichsen – Extreme availability and self-healing data with CRDTs - No...Uwe Friedrichsen – Extreme availability and self-healing data with CRDTs - No...
Uwe Friedrichsen – Extreme availability and self-healing data with CRDTs - No...
 
Pi j3.4 data-structures
Pi j3.4 data-structuresPi j3.4 data-structures
Pi j3.4 data-structures
 
LSGAN - SIMPle(Simple Idea Meaningful Performance Level up)
LSGAN - SIMPle(Simple Idea Meaningful Performance Level up)LSGAN - SIMPle(Simple Idea Meaningful Performance Level up)
LSGAN - SIMPle(Simple Idea Meaningful Performance Level up)
 
A Tale of Two Graph Frameworks on Spark: GraphFrames and Tinkerpop OLAP Artem...
A Tale of Two Graph Frameworks on Spark: GraphFrames and Tinkerpop OLAP Artem...A Tale of Two Graph Frameworks on Spark: GraphFrames and Tinkerpop OLAP Artem...
A Tale of Two Graph Frameworks on Spark: GraphFrames and Tinkerpop OLAP Artem...
 

Similar a 15 unionfind

The Power of Motif Counting Theory, Algorithms, and Applications for Large Gr...
The Power of Motif Counting Theory, Algorithms, and Applications for Large Gr...The Power of Motif Counting Theory, Algorithms, and Applications for Large Gr...
The Power of Motif Counting Theory, Algorithms, and Applications for Large Gr...Nesreen K. Ahmed
 
PGQL: A Language for Graphs
PGQL: A Language for GraphsPGQL: A Language for Graphs
PGQL: A Language for GraphsJean Ihm
 
Follow the money with graphs
Follow the money with graphsFollow the money with graphs
Follow the money with graphsStanka Dalekova
 
Towards Set Learning and Prediction - Laura Leal-Taixe - UPC Barcelona 2018
Towards Set Learning and Prediction - Laura Leal-Taixe - UPC Barcelona 2018Towards Set Learning and Prediction - Laura Leal-Taixe - UPC Barcelona 2018
Towards Set Learning and Prediction - Laura Leal-Taixe - UPC Barcelona 2018Universitat Politècnica de Catalunya
 
8th TUC Meeting | Lijun Chang (University of New South Wales). Efficient Subg...
8th TUC Meeting | Lijun Chang (University of New South Wales). Efficient Subg...8th TUC Meeting | Lijun Chang (University of New South Wales). Efficient Subg...
8th TUC Meeting | Lijun Chang (University of New South Wales). Efficient Subg...LDBC council
 
Mining Regular Patterns in Data Streams Using Vertical Format
Mining Regular Patterns in Data Streams Using Vertical FormatMining Regular Patterns in Data Streams Using Vertical Format
Mining Regular Patterns in Data Streams Using Vertical FormatCSCJournals
 
From grep to BERT
From grep to BERTFrom grep to BERT
From grep to BERTQAware GmbH
 
IA3_presentation.pptx
IA3_presentation.pptxIA3_presentation.pptx
IA3_presentation.pptxKtonNguyn2
 
2015 bioinformatics alignments_wim_vancriekinge
2015 bioinformatics alignments_wim_vancriekinge2015 bioinformatics alignments_wim_vancriekinge
2015 bioinformatics alignments_wim_vancriekingeProf. Wim Van Criekinge
 
5 parallel implementation 06299286
5 parallel implementation 062992865 parallel implementation 06299286
5 parallel implementation 06299286Ninad Samel
 
2016 bioinformatics i_alignments_wim_vancriekinge
2016 bioinformatics i_alignments_wim_vancriekinge2016 bioinformatics i_alignments_wim_vancriekinge
2016 bioinformatics i_alignments_wim_vancriekingeProf. Wim Van Criekinge
 
Tutorial "Linked Data Query Processing" Part 2 "Theoretical Foundations" (WWW...
Tutorial "Linked Data Query Processing" Part 2 "Theoretical Foundations" (WWW...Tutorial "Linked Data Query Processing" Part 2 "Theoretical Foundations" (WWW...
Tutorial "Linked Data Query Processing" Part 2 "Theoretical Foundations" (WWW...Olaf Hartig
 
Recommendation and graph algorithms in Hadoop and SQL
Recommendation and graph algorithms in Hadoop and SQLRecommendation and graph algorithms in Hadoop and SQL
Recommendation and graph algorithms in Hadoop and SQLDavid Gleich
 
Scalable frequent itemset mining using heterogeneous computing par apriori a...
Scalable frequent itemset mining using heterogeneous computing  par apriori a...Scalable frequent itemset mining using heterogeneous computing  par apriori a...
Scalable frequent itemset mining using heterogeneous computing par apriori a...ijdpsjournal
 
IEEE Datamining 2016 Title and Abstract
IEEE  Datamining 2016 Title and AbstractIEEE  Datamining 2016 Title and Abstract
IEEE Datamining 2016 Title and Abstracttsysglobalsolutions
 
Interactive Knowledge Discovery over Web of Data.
Interactive Knowledge Discovery over Web of Data.Interactive Knowledge Discovery over Web of Data.
Interactive Knowledge Discovery over Web of Data.Mehwish Alam
 
Uwe Friedrichsen - CRDT und mehr - über extreme Verfügbarkeit und selbstheile...
Uwe Friedrichsen - CRDT und mehr - über extreme Verfügbarkeit und selbstheile...Uwe Friedrichsen - CRDT und mehr - über extreme Verfügbarkeit und selbstheile...
Uwe Friedrichsen - CRDT und mehr - über extreme Verfügbarkeit und selbstheile...AboutYouGmbH
 

Similar a 15 unionfind (20)

The Power of Motif Counting Theory, Algorithms, and Applications for Large Gr...
The Power of Motif Counting Theory, Algorithms, and Applications for Large Gr...The Power of Motif Counting Theory, Algorithms, and Applications for Large Gr...
The Power of Motif Counting Theory, Algorithms, and Applications for Large Gr...
 
PGQL: A Language for Graphs
PGQL: A Language for GraphsPGQL: A Language for Graphs
PGQL: A Language for Graphs
 
Follow the money with graphs
Follow the money with graphsFollow the money with graphs
Follow the money with graphs
 
Bioinformatics t4-alignments v2014
Bioinformatics t4-alignments v2014Bioinformatics t4-alignments v2014
Bioinformatics t4-alignments v2014
 
Algorithm
AlgorithmAlgorithm
Algorithm
 
Towards Set Learning and Prediction - Laura Leal-Taixe - UPC Barcelona 2018
Towards Set Learning and Prediction - Laura Leal-Taixe - UPC Barcelona 2018Towards Set Learning and Prediction - Laura Leal-Taixe - UPC Barcelona 2018
Towards Set Learning and Prediction - Laura Leal-Taixe - UPC Barcelona 2018
 
8th TUC Meeting | Lijun Chang (University of New South Wales). Efficient Subg...
8th TUC Meeting | Lijun Chang (University of New South Wales). Efficient Subg...8th TUC Meeting | Lijun Chang (University of New South Wales). Efficient Subg...
8th TUC Meeting | Lijun Chang (University of New South Wales). Efficient Subg...
 
Mining Regular Patterns in Data Streams Using Vertical Format
Mining Regular Patterns in Data Streams Using Vertical FormatMining Regular Patterns in Data Streams Using Vertical Format
Mining Regular Patterns in Data Streams Using Vertical Format
 
From grep to BERT
From grep to BERTFrom grep to BERT
From grep to BERT
 
IA3_presentation.pptx
IA3_presentation.pptxIA3_presentation.pptx
IA3_presentation.pptx
 
2015 bioinformatics alignments_wim_vancriekinge
2015 bioinformatics alignments_wim_vancriekinge2015 bioinformatics alignments_wim_vancriekinge
2015 bioinformatics alignments_wim_vancriekinge
 
5 parallel implementation 06299286
5 parallel implementation 062992865 parallel implementation 06299286
5 parallel implementation 06299286
 
2016 bioinformatics i_alignments_wim_vancriekinge
2016 bioinformatics i_alignments_wim_vancriekinge2016 bioinformatics i_alignments_wim_vancriekinge
2016 bioinformatics i_alignments_wim_vancriekinge
 
Tutorial "Linked Data Query Processing" Part 2 "Theoretical Foundations" (WWW...
Tutorial "Linked Data Query Processing" Part 2 "Theoretical Foundations" (WWW...Tutorial "Linked Data Query Processing" Part 2 "Theoretical Foundations" (WWW...
Tutorial "Linked Data Query Processing" Part 2 "Theoretical Foundations" (WWW...
 
50120130406039
5012013040603950120130406039
50120130406039
 
Recommendation and graph algorithms in Hadoop and SQL
Recommendation and graph algorithms in Hadoop and SQLRecommendation and graph algorithms in Hadoop and SQL
Recommendation and graph algorithms in Hadoop and SQL
 
Scalable frequent itemset mining using heterogeneous computing par apriori a...
Scalable frequent itemset mining using heterogeneous computing  par apriori a...Scalable frequent itemset mining using heterogeneous computing  par apriori a...
Scalable frequent itemset mining using heterogeneous computing par apriori a...
 
IEEE Datamining 2016 Title and Abstract
IEEE  Datamining 2016 Title and AbstractIEEE  Datamining 2016 Title and Abstract
IEEE Datamining 2016 Title and Abstract
 
Interactive Knowledge Discovery over Web of Data.
Interactive Knowledge Discovery over Web of Data.Interactive Knowledge Discovery over Web of Data.
Interactive Knowledge Discovery over Web of Data.
 
Uwe Friedrichsen - CRDT und mehr - über extreme Verfügbarkeit und selbstheile...
Uwe Friedrichsen - CRDT und mehr - über extreme Verfügbarkeit und selbstheile...Uwe Friedrichsen - CRDT und mehr - über extreme Verfügbarkeit und selbstheile...
Uwe Friedrichsen - CRDT und mehr - über extreme Verfügbarkeit und selbstheile...
 

Último

CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service 🪡
CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service  🪡CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service  🪡
CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service 🪡anilsa9823
 
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral AnalysisRaman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral AnalysisDiwakar Mishra
 
Natural Polymer Based Nanomaterials
Natural Polymer Based NanomaterialsNatural Polymer Based Nanomaterials
Natural Polymer Based NanomaterialsAArockiyaNisha
 
fundamental of entomology all in one topics of entomology
fundamental of entomology all in one topics of entomologyfundamental of entomology all in one topics of entomology
fundamental of entomology all in one topics of entomologyDrAnita Sharma
 
Pulmonary drug delivery system M.pharm -2nd sem P'ceutics
Pulmonary drug delivery system M.pharm -2nd sem P'ceuticsPulmonary drug delivery system M.pharm -2nd sem P'ceutics
Pulmonary drug delivery system M.pharm -2nd sem P'ceuticssakshisoni2385
 
GBSN - Microbiology (Unit 1)
GBSN - Microbiology (Unit 1)GBSN - Microbiology (Unit 1)
GBSN - Microbiology (Unit 1)Areesha Ahmad
 
Forensic Biology & Its biological significance.pdf
Forensic Biology & Its biological significance.pdfForensic Biology & Its biological significance.pdf
Forensic Biology & Its biological significance.pdfrohankumarsinghrore1
 
VIRUSES structure and classification ppt by Dr.Prince C P
VIRUSES structure and classification ppt by Dr.Prince C PVIRUSES structure and classification ppt by Dr.Prince C P
VIRUSES structure and classification ppt by Dr.Prince C PPRINCE C P
 
Botany 4th semester series (krishna).pdf
Botany 4th semester series (krishna).pdfBotany 4th semester series (krishna).pdf
Botany 4th semester series (krishna).pdfSumit Kumar yadav
 
Nanoparticles synthesis and characterization​ ​
Nanoparticles synthesis and characterization​  ​Nanoparticles synthesis and characterization​  ​
Nanoparticles synthesis and characterization​ ​kaibalyasahoo82800
 
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCRStunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCRDelhi Call girls
 
Green chemistry and Sustainable development.pptx
Green chemistry  and Sustainable development.pptxGreen chemistry  and Sustainable development.pptx
Green chemistry and Sustainable development.pptxRajatChauhan518211
 
Chemistry 4th semester series (krishna).pdf
Chemistry 4th semester series (krishna).pdfChemistry 4th semester series (krishna).pdf
Chemistry 4th semester series (krishna).pdfSumit Kumar yadav
 
PossibleEoarcheanRecordsoftheGeomagneticFieldPreservedintheIsuaSupracrustalBe...
PossibleEoarcheanRecordsoftheGeomagneticFieldPreservedintheIsuaSupracrustalBe...PossibleEoarcheanRecordsoftheGeomagneticFieldPreservedintheIsuaSupracrustalBe...
PossibleEoarcheanRecordsoftheGeomagneticFieldPreservedintheIsuaSupracrustalBe...Sérgio Sacani
 
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43bNightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43bSérgio Sacani
 
Animal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptxAnimal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptxUmerFayaz5
 
GBSN - Microbiology (Unit 2)
GBSN - Microbiology (Unit 2)GBSN - Microbiology (Unit 2)
GBSN - Microbiology (Unit 2)Areesha Ahmad
 
Hubble Asteroid Hunter III. Physical properties of newly found asteroids
Hubble Asteroid Hunter III. Physical properties of newly found asteroidsHubble Asteroid Hunter III. Physical properties of newly found asteroids
Hubble Asteroid Hunter III. Physical properties of newly found asteroidsSérgio Sacani
 
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...Sérgio Sacani
 
Isotopic evidence of long-lived volcanism on Io
Isotopic evidence of long-lived volcanism on IoIsotopic evidence of long-lived volcanism on Io
Isotopic evidence of long-lived volcanism on IoSérgio Sacani
 

Último (20)

CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service 🪡
CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service  🪡CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service  🪡
CALL ON ➥8923113531 🔝Call Girls Kesar Bagh Lucknow best Night Fun service 🪡
 
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral AnalysisRaman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
 
Natural Polymer Based Nanomaterials
Natural Polymer Based NanomaterialsNatural Polymer Based Nanomaterials
Natural Polymer Based Nanomaterials
 
fundamental of entomology all in one topics of entomology
fundamental of entomology all in one topics of entomologyfundamental of entomology all in one topics of entomology
fundamental of entomology all in one topics of entomology
 
Pulmonary drug delivery system M.pharm -2nd sem P'ceutics
Pulmonary drug delivery system M.pharm -2nd sem P'ceuticsPulmonary drug delivery system M.pharm -2nd sem P'ceutics
Pulmonary drug delivery system M.pharm -2nd sem P'ceutics
 
GBSN - Microbiology (Unit 1)
GBSN - Microbiology (Unit 1)GBSN - Microbiology (Unit 1)
GBSN - Microbiology (Unit 1)
 
Forensic Biology & Its biological significance.pdf
Forensic Biology & Its biological significance.pdfForensic Biology & Its biological significance.pdf
Forensic Biology & Its biological significance.pdf
 
VIRUSES structure and classification ppt by Dr.Prince C P
VIRUSES structure and classification ppt by Dr.Prince C PVIRUSES structure and classification ppt by Dr.Prince C P
VIRUSES structure and classification ppt by Dr.Prince C P
 
Botany 4th semester series (krishna).pdf
Botany 4th semester series (krishna).pdfBotany 4th semester series (krishna).pdf
Botany 4th semester series (krishna).pdf
 
Nanoparticles synthesis and characterization​ ​
Nanoparticles synthesis and characterization​  ​Nanoparticles synthesis and characterization​  ​
Nanoparticles synthesis and characterization​ ​
 
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCRStunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
 
Green chemistry and Sustainable development.pptx
Green chemistry  and Sustainable development.pptxGreen chemistry  and Sustainable development.pptx
Green chemistry and Sustainable development.pptx
 
Chemistry 4th semester series (krishna).pdf
Chemistry 4th semester series (krishna).pdfChemistry 4th semester series (krishna).pdf
Chemistry 4th semester series (krishna).pdf
 
PossibleEoarcheanRecordsoftheGeomagneticFieldPreservedintheIsuaSupracrustalBe...
PossibleEoarcheanRecordsoftheGeomagneticFieldPreservedintheIsuaSupracrustalBe...PossibleEoarcheanRecordsoftheGeomagneticFieldPreservedintheIsuaSupracrustalBe...
PossibleEoarcheanRecordsoftheGeomagneticFieldPreservedintheIsuaSupracrustalBe...
 
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43bNightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
 
Animal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptxAnimal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptx
 
GBSN - Microbiology (Unit 2)
GBSN - Microbiology (Unit 2)GBSN - Microbiology (Unit 2)
GBSN - Microbiology (Unit 2)
 
Hubble Asteroid Hunter III. Physical properties of newly found asteroids
Hubble Asteroid Hunter III. Physical properties of newly found asteroidsHubble Asteroid Hunter III. Physical properties of newly found asteroids
Hubble Asteroid Hunter III. Physical properties of newly found asteroids
 
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
 
Isotopic evidence of long-lived volcanism on Io
Isotopic evidence of long-lived volcanism on IoIsotopic evidence of long-lived volcanism on Io
Isotopic evidence of long-lived volcanism on Io
 

15 unionfind

  • 1. ROBERT SEDGEWICK | KEVIN WAYNE F O U R T H E D I T I O N Algorithms http://algs4.cs.princeton.edu Algorithms ROBERT SEDGEWICK | KEVIN WAYNE ‣ 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. 2 Subtext of today’s lecture (and this course)
  • 3. http://algs4.cs.princeton.edu ROBERT SEDGEWICK | KEVIN WAYNE Algorithms ‣ dynamic connectivity ‣ quick find ‣ quick union ‣ improvements ‣ applications 1.5 UNION-FIND
  • 4. Given a set of N objects. ・Union command: connect two objects. ・Find/connected query: is there a path connecting the two objects? 4 Dynamic connectivity union(4, 3) union(3, 8) union(6, 5) union(9, 4) union(2, 1) connected(0, 7) connected(8, 9) union(5, 0) union(7, 2) connected(0, 7) union(1, 0) union(6, 1) 0 1 2 3 4 5 6 7 8 9 𐄂 ✔ ✔
  • 5. Q. Is there a path connecting p and q ? A. Yes. 5 Connectivity example p q
  • 6. 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 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. 6 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. 7 Modeling the connections { 0 } { 1 4 5 } { 2 3 6 7 } 3 connected components 0 1 2 3 4 5 6 7
  • 8. Find query. Check if two objects are in the same component. Union command. Replace components containing two objects with their union. 8 Implementing the operations { 0 } { 1 4 5 } { 2 3 6 7 } 3 connected components 0 1 2 3 4 5 6 7 union(2, 5) { 0 } { 1 2 3 4 5 6 7 } 2 connected components 0 1 2 3 4 5 6 7
  • 9. 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 UFpublic class UFpublic class UF UF(int N) initialize union-find data structure with N objects (0 to N – 1) void union(int p, int q) add connection between p and q boolean connected(int p, int q) are p and q in the same component? int find(int p) component identifier for p (0 to N – 1) int count() number of components
  • 10. 10 ・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 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)) { 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
  • 11. http://algs4.cs.princeton.edu ROBERT SEDGEWICK | KEVIN WAYNE Algorithms ‣ dynamic connectivity ‣ quick find ‣ quick union ‣ improvements ‣ applications 1.5 UNION-FIND
  • 12. http://algs4.cs.princeton.edu ROBERT SEDGEWICK | KEVIN WAYNE Algorithms ‣ dynamic connectivity ‣ quick find ‣ quick union ‣ improvements ‣ applications 1.5 UNION-FIND
  • 13. 13 Data structure. ・Integer array id[] of length N. ・Interpretation: p and q are connected iff they have the same id. 0, 5 and 6 are connected 1, 2, and 7 are connected 3, 4, 8, and 9 are connected Quick-find [eager approach] 0 1 2 3 4 5 6 7 8 9 0 1 0 1 1 8 2 3 8 0 4 5 0 1 6 7 8 8 8 9 id[] if and only if
  • 14. 14 Data structure. ・Integer array id[] of length N. ・Interpretation: p and q are connected iff they have the same id. Find. Check if p and q have the same id. Union. To merge components containing p and q, change all entries whose id equals id[p] to id[q]. after union of 6 and 1 problem: many values can change Quick-find [eager approach] id[6] = 0; id[1] = 1 6 and 1 are not connected 0 1 0 1 1 8 2 3 8 0 4 5 0 1 6 7 8 8 8 9 1 1 0 1 1 8 2 3 8 1 4 5 1 1 6 7 8 8 8 9 id[] id[]
  • 15. 15 Quick-find demo 0 1 2 3 4 5 6 7 8 9 0 1 0 1 2 3 2 3 4 5 4 5 6 7 6 7 8 9 8 9 id[]
  • 16. Quick-find demo 0 1 2 3 4 5 6 7 8 9 1 1 0 1 1 8 2 3 8 1 4 5 1 1 6 7 8 8 8 9 id[]
  • 17. 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; } } 17 Quick-find: Java implementation set id of each object to itself (N array accesses) change all entries with id[p] to id[q] (at most 2N + 2 array accesses) check whether p and q are in the same component (2 array accesses)
  • 18. Cost model. Number of array accesses (for read or write). Union is too expensive. It takes N 2 array accesses to process a sequence of N union commands on N objects. 18 Quick-find is too slow algorithm initialize union find quick-find N N 1 order of growth of number of array accesses quadratic
  • 19. Rough standard (for now). ・109 operations per second. ・109 words of main memory. ・Touch all words in approximately 1 second. Ex. Huge problem for quick-find. ・109 union commands on 109 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! 19 a truism (roughly) since 1950! Quadratic algorithms do not scale 8T 16T 32T 64T time 1K 2K 4K 8Ksize quadratic linearithmic linear
  • 20. http://algs4.cs.princeton.edu ROBERT SEDGEWICK | KEVIN WAYNE Algorithms ‣ dynamic connectivity ‣ quick find ‣ quick union ‣ improvements ‣ applications 1.5 UNION-FIND
  • 21. http://algs4.cs.princeton.edu ROBERT SEDGEWICK | KEVIN WAYNE Algorithms ‣ dynamic connectivity ‣ quick find ‣ quick union ‣ improvements ‣ applications 1.5 UNION-FIND
  • 22. Data structure. ・Integer array id[] of length N. ・Interpretation: id[i] is parent of i. ・Root of i is id[id[id[...id[i]...]]]. 22 root of 3 is 9 Quick-union [lazy approach] keep going until it doesn’t change (algorithm ensures no cycles) 0 1 0 1 9 4 2 3 9 6 4 5 6 7 6 7 8 9 8 9 id[] 3 54 70 1 9 6 8 2
  • 23. Data structure. ・Integer array id[] of length 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 components containing p and q, set the id of p's root to the id of q's root. 23 Quick-union [lazy approach] 0 1 0 1 9 4 2 3 9 6 4 5 6 7 6 7 8 9 8 9 id[] 3 4 70 1 9 6 8 2 only one value changes p q 0 1 0 1 9 4 2 3 9 6 4 5 6 7 6 7 8 6 8 9 id[] 5 3 54 70 1 9 6 8 2 p q root of 3 is 9 root of 5 is 6 3 and 5 are not connected
  • 24. 24 Quick-union demo 0 1 2 3 4 5 6 7 8 9 0 1 0 1 2 3 2 3 4 5 4 5 6 7 6 7 8 9 8 9 id[]
  • 25. Quick-union demo 0 1 2 5 6 7 3 4 8 9 1 8 0 1 1 8 2 3 3 0 4 5 5 1 6 7 8 8 8 9 id[]
  • 26. 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); int 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
  • 27. 27 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 roots Quick-union is also too slow algorithm initialize union find quick-find N N 1 quick-union N N † N
  • 28. http://algs4.cs.princeton.edu ROBERT SEDGEWICK | KEVIN WAYNE Algorithms ‣ dynamic connectivity ‣ quick find ‣ quick union ‣ improvements ‣ applications 1.5 UNION-FIND
  • 29. http://algs4.cs.princeton.edu ROBERT SEDGEWICK | KEVIN WAYNE Algorithms ‣ dynamic connectivity ‣ quick find ‣ quick union ‣ improvements ‣ applications 1.5 UNION-FIND
  • 30. 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. 30 Improvement 1: weighting smaller tree larger tree q p smaller tree larger tree q p smaller tree larger tree q p smaller tree larger tree q p Weighted quick-union weighted quick-union always chooses the better alternative might put the larger tree lower reasonable alternatives: union by height or "rank"
  • 31. 31 Weighted quick-union demo 0 1 2 3 4 5 6 7 8 9 0 1 0 1 2 3 2 3 4 5 4 5 6 7 6 7 8 9 8 9 id[]
  • 32. Weighted quick-union demo 98 4 3 71 2 50 6 6 2 0 1 6 4 2 3 6 6 4 5 6 2 6 7 4 4 8 9 id[]
  • 33. 33 Quick-union and weighted quick-union example Quick-union and weighted quick-union (100 sites, 88 union() operations) weighted quick-union average distance to root: 1.52 average distance to root: 5.11
  • 34. 34 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: ・Link root of smaller tree to root of larger tree. ・Update the sz[] array. int i = root(p); int j = root(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]; } Weighted quick-union: Java implementation return root(p) == root(q);
  • 35. 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. 35 Weighted quick-union analysis lg = base-2 logarithm x N = 10 depth(x) = 3 ≤ lg N
  • 36. 36 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 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? Weighted quick-union analysis T2 T1 x
  • 37. 37 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 roots Weighted quick-union analysis algorithm initialize union connected quick-find N N 1 quick-union N N † N weighted QU N lg N † lg N
  • 38. Quick union with path compression. Just after computing the root of p, set the id of each examined node to point to that root. 38 Improvement 2: path compression 1211 9 10 8 6 7 3 x 2 54 0 1 root p
  • 39. Quick union with path compression. Just after computing the root of p, set the id of each examined node to point to that root. 39 Improvement 2: path compression 10 8 6 7 31211 9 2 54 0 1 root x p
  • 40. Quick union with path compression. Just after computing the root of p, set the id of each examined node to point to that root. 40 Improvement 2: path compression 7 3 10 8 6 1211 9 2 54 0 1 root x p
  • 41. Quick union with path compression. Just after computing the root of p, set the id of each examined node to point to that root. 41 Improvement 2: path compression 10 8 6 2 54 0 1 7 3 root x p 1211 9
  • 42. Quick union with path compression. Just after computing the root of p, set the id of each examined node to point to that root. 42 Improvement 2: path compression 10 8 6 7 3 x root 2 54 0 1 p 1211 9
  • 43. Two-pass implementation: add second loop to root() to set the id[] of each examined node to the root. Simpler one-pass variant: Make every other node in path point to its grandparent (thereby halving path length). In practice. No reason not to! Keeps tree almost completely flat. 43 Path compression: Java implementation only one extra line of code ! private int root(int i) { while (i != id[i]) { id[i] = id[id[i]]; i = id[i]; } return i; }
  • 44. 44 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. 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. [Fredman-Saks] No linear-time algorithm exists. N lg* N 1 0 2 1 4 2 16 3 65536 4 265536 5 Weighted quick-union with path compression: amortized analysis iterate log function in "cell-probe" model of computation
  • 45. Bottom line. Weighted quick union (with path compression) makes it possible to solve problems that could not otherwise be addressed. Ex. [109 unions and finds with 109 objects] ・WQUPC reduces time from 30 years to 6 seconds. ・Supercomputer won't help much; good algorithm enables solution. 45 M union-find operations on a set of N objects algorithm worst-case time quick-find M N quick-union M N weighted QU N + M log N QU + path compression N + M log N weighted QU + path compression N + M lg* N Summary
  • 46. http://algs4.cs.princeton.edu ROBERT SEDGEWICK | KEVIN WAYNE Algorithms ‣ dynamic connectivity ‣ quick find ‣ quick union ‣ improvements ‣ applications 1.5 UNION-FIND
  • 47. http://algs4.cs.princeton.edu ROBERT SEDGEWICK | KEVIN WAYNE Algorithms ‣ dynamic connectivity ‣ quick find ‣ quick union ‣ improvements ‣ applications 1.5 UNION-FIND
  • 48. 48 ・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
  • 49. 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. 49 Percolation N = 8 does not percolatepercolates open site connected to top blocked site open site no open site connected to top
  • 50. 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. 50 model system vacant site occupied site percolates electricity material conductor insulated conducts fluid flow material empty blocked porous social interaction population person empty communicates Percolation
  • 51. Depends on site vacancy probability p. 51 Likelihood of percolation p low (0.4) does not percolate p medium (0.6) percolates? p high (0.8) percolates
  • 52. 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* ? 52 Percolation phase transition 0.5930 0 1 1 site vacancy probability p percolation probability p* N = 100
  • 53. ・Initialize N-by-N whole grid to be blocked. ・Declare random sites open until top connected to bottom. ・Vacancy percentage estimates p*. 53 Monte Carlo simulation N = 20 empty open site (not connected to top) full open site (connected to top) blocked site
  • 54. 54 Q. How to check whether an N-by-N system percolates? Dynamic connectivity solution to estimate percolation threshold open site blocked site N = 5
  • 55. 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. 55 Dynamic connectivity solution to estimate percolation threshold open site blocked site 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
  • 56. 56 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 if connected by open sites. Dynamic connectivity solution to estimate percolation threshold open site blocked site N = 5
  • 57. 57 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 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 top row bottom row
  • 58. Clever trick. Introduce 2 virtual sites (and connections to top and bottom). ・Percolates iff virtual top site is connected to virtual bottom site. 58 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 top row bottom row
  • 59. Q. How to model opening a new site? 59 Dynamic connectivity solution to estimate percolation threshold open site blocked site N = 5 open this site
  • 60. Q. How to model opening a new site? A. Mark new site as open; connect it to all of its adjacent open sites. 60 Dynamic connectivity solution to estimate percolation threshold open this site open site blocked site N = 5 up to 4 calls to union()
  • 61. 61 Q. What is percolation threshold p* ? A. About 0.592746 for large square lattices. Fast algorithm enables accurate answer to scientific question. constant known only via simulation Percolation threshold 0.5930 0 1 1 site vacancy probability p percolation probability p* N = 100
  • 62. http://algs4.cs.princeton.edu ROBERT SEDGEWICK | KEVIN WAYNE Algorithms ‣ dynamic connectivity ‣ quick find ‣ quick union ‣ improvements ‣ applications 1.5 UNION-FIND
  • 63. 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. 63 Subtext of today’s lecture (and this course)
  • 64. ROBERT SEDGEWICK | KEVIN WAYNE F O U R T H E D I T I O N Algorithms http://algs4.cs.princeton.edu Algorithms ROBERT SEDGEWICK | KEVIN WAYNE ‣ dynamic connectivity ‣ quick find ‣ quick union ‣ improvements ‣ applications 1.5 UNION-FIND