-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlca_using_sparse_table.cpp
74 lines (63 loc) · 1.4 KB
/
lca_using_sparse_table.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//LCA using sparse table
//Complexity: O(NlgN,lgN)
#include<bits/stdc++.h>
using namespace std;
#define mx 100002
#define pb push_back
int L[mx]; //?????
int P[mx][22]; //??????? ?????
int T[mx]; //?????????
vector<int>g[mx];
void dfs(int from,int u,int dep)
{
T[u]=from;
L[u]=dep;
for(int i=0;i<(int)g[u].size();i++)
{
int v=g[u][i];
if(v==from) continue;
dfs(u,v,dep+1);
}
}
int lca_query(int N, int p, int q) //N=???? ??????
{
int tmp, log, i;
if (L[p] < L[q])
tmp = p, p = q, q = tmp;
log=1;
while(1) {
int next=log+1;
if((1<<next)>L[p])break;
log++;
}
for (i = log; i >= 0; i--)
if (L[p] - (1 << i) >= L[q])
p = P[p][i];
if (p == q)
return p;
for (i = log; i >= 0; i--)
if (P[p][i] != -1 && P[p][i] != P[q][i])
p = P[p][i], q = P[q][i];
return T[p];
}
void lca_init(int N)
{
memset (P,-1,sizeof(P)); //?????? ??????? ??? -? ?????
int i, j;
for (i = 0; i < N; i++)
P[i][0] = T[i];
for (j = 1; 1 << j < N; j++)
for (i = 0; i < N; i++)
if (P[i][j - 1] != -1)
P[i][j] = P[P[i][j - 1]][j - 1];
}
int main(void) {
g[0].pb(1);
g[0].pb(2);
g[2].pb(3);
g[2].pb(4);
dfs(0, 0, 0);
lca_init(5);
printf( "%d\n", lca_query(5,3,4) );
return 0;
}