Upload
orla-herring
View
14
Download
0
Embed Size (px)
DESCRIPTION
Lowest common ancestors. 0. Shallowest node. 12. 8. 3. 9. 1. 2. 11. 4. 7. 10. 5. 6. Write an Euler tour of the tree. 3. 3. 2. 3. 1. 4. 1. 7. 1. 3. 5. 6. 5. 3. 5. 1. 2. 4. 6. 7. LCA(1,5) = 3. 0. minimum. 12. 8. 3. 9. 1. 2. 11. 4. 7. 10. 5. 6. 3. 5. - PowerPoint PPT Presentation
Citation preview
Lowest common ancestors
Write an Euler tour of the tree
3
4
51
672
4 1 7 1 3 5 6 5 33 1231
2
3
4
6
9
10
8
57
11
12
0
LCA(1,5) = 3
Shallowest node
3
4
51
672
4 1 7 1 3 5 6 5 33 123
1
2
3
4
6
9
10
8
57
11
12
0
2 1 2 1 0 1 2 1 00 110
minimum
Range minimum
3
4
51
672
4 1 7 1 3 5 6 5 33 123
1
2
3
4
6
9
10
8
57
11
12
0
2 1 2 1 0 1 2 1 00 110
minimum
Preprocess an array, such that given i,j you can find the minimum in [i,j] fast
Reduction takes linear time
Trivial algorithms for RMQ
Less trivial algorithms to RMQ
• Try to use O(nlog(n)) space to do a query in O(1) time
... ... .........blocksn log
2n
… ...B[0] B[2n/logn]B[i]
… ...A’[0] A’[2n/logn]A’[i]
Rememeber the min in each block (A’) and its position (B)
Optimal solution
10 337 2634 9 2 1225 22
0 21 93 4 5 6 7 8 10 11 12 13 14 15
24 43 5 11 19 27
n=16A[] :
10 25 22 7 34 9 … blocksn log
2n =8
10 7 9
0 21A’[] :
… 0 3 5
0 21B[] :
…
Example
Preprocess A’ for RMQ using the O(nlog(n)) space algorithm.
Since the size of A’ is this would take
2
log
n
n
2 2log( ) ( )
log log
n nO n
n n Space,
preprocessing time
i and j might be in the same block, we need some mechanism to answer inside blocks
i < j on different blocks, answer the query as follows:
1. Compute minima from i to end of its block.2. Compute minima of all blocks in between i’s and j’s
blocks.3. Compute minima from the beginning of j’s block to j.
Return the index of the minimum of these 3 values.
How do we answer queries ?
So what do we do inside blocks?
We need to solve a special case of RMQ
3
4
51
672
4 1 7 1 3 5 6 5 33 123
1
2
3
4
6
9
10
8
57
11
12
0
2 1 2 1 0 1 2 1 00 110
1 restriction
0 13 2 2 1 2 3 1 2
+1 -1 -1-1 +1 +1 -1+1 +1
Each subproblem can be described by the first entry and a vector of ±1
Two subproblems with the same vector of ±1 are equivalent
3 4 6 5 5 4 5 6 4 5
The bottom line
There aren’t too many different subproblems, only
log1
22 ( )n
O n
For each such subproblem prepare all answers in advance 2log ( )O n n o n
n
Pick a subproblem:
Find the solution using i,j:
... ... .........blocksn log
2n
… ...B[0] B[2n/logn]B[i]
… ...A’[0] A’[2n/logn]A’[i]
Summary
Each block know its subproblem (A’’)
… ...A’’[0] A’’[2n/logn]A’’[i]