Академический Документы
Профессиональный Документы
Культура Документы
Jaehyun Park
CS 97SI
Stanford University
void quarter() {
while(true) { // no break :(
task x = GetNextTask(tasks);
process(x);
// new tasks may enter
}
}
Returns
Returns
Returns
Returns
the
the
the
the
Outline
Stack
Stack Implementation
Queue
Queue Implementation
Outline
Priority Queue
10
Heap
11
Heap Example
12
13
Inserting a Node
2. If the new node breaks the heap property, swap with its parent
node
The new node moves up the tree, which may introduce
another conict
14
15
1. Remove the root, and bring the last node (rightmost node in
the last level) to the root
2. If the root breaks the heap property, look at its children and
swap it with the larger one
Swapping can introduce another conict
16
Outline
Union-Find Structure
17
Union-Find Structure
Super-short implementation!
Union-Find Structure
18
Union-Find Structure
Union-Find Structure
19
Implementation Idea
Union-Find Structure
20
Implementation
int Find(int x) {
while(x != L[x]) x = L[x];
return x;
}
void Union(int x, int y) {
L[Find(x)] = Find(y);
}
Union-Find Structure
21
Path Compression
Union-Find Structure
22
int Find(int x) {
if(x == L[x]) return x;
int root = Find(L[x]);
L[x] = root;
return root;
}
int Find(int x) {
return x == L[x] ? x : L[x] = Find(L[x]);
}
Union-Find Structure
23
Outline
24
25
26
27
Outline
Fenwick Tree
28
Fenwick Tree
Fenwick Tree
29
Fenwick Tree
30
Main idea: choose the minimal set of nodes whose sum gives
the desired value
We will see that
at most 1 node is chosen at each level so that the total
number of nodes we look at is log2 n
and this can be done in O(log n) time
Fenwick Tree
31
Summing: Example 1
Fenwick Tree
32
Summing: Example 2
Sum(8)
Fenwick Tree
33
Summing: Example 3
Sum(6)
Fenwick Tree
34
Summing: Example 4
Sum(3)
Fenwick Tree
35
Otherwise:
Fenwick Tree
36
Updating a Value
Fenwick Tree
37
Extension
Fenwick Tree
38
Outline
39
40
Preprocessing
Computing Anc[x][k]:
Anc[x][0] = xs parent
Anc[x][k] = Anc[ Anc[x][k-1] ][ k-1 ]
41
Answering a Query
42
Answering a Query
Decrease k by 1
Otherwise:
43
Conclusion
44