- O(logn)(n<=10^6)
- https://www.cnblogs.com/cangT-Tlan/p/8846408.html
- The tree is divided into a chain of several, to maintain a data structure of each chain
-
1 #include<bits/stdc++.h> 2 #define ll long long 3 #define rll register ll 4 #define M 0x3f3f3f 5 #define For(i,l,r) for(int i=l;i<=r;i++) 6 using namespace std; 7 ll n,m,s,head[M],a[M],x,y,z,tot,k,t; 8 ll fa[M],d[M],top[M],size[M],id[M],ril[M]; 9 struct node1{ 10 ll to,nxt; 11 }e[M<<1]; 12 struct node2{ 13 ll l,r,sum,flag; 14 }tree[M<<1]; 15 16 inline ll read(){ 17 ll f=1,sum=0; 18 char ch=getchar(); 19 while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();} 20 while(isdigit(ch)){sum=(sum<<1)+(sum<<3)+(ch^48);ch=getchar();} 21 return f*sum; 22 } 23 24 inline void add(ll x,ll y){ 25 E [++ TOT] .to = Y; 26 is E [TOT] = .nxt head [X]; 27 head [X] = TOT; 28 } 29 30 inline void DFS1 (U LL) { // first pass dfs tree traversal, the depth d pretreatment, size this point node number, FA parent node 31 is d [U] = d [FA [U]] + . 1 ; 32 size [U] = . 1 ; 33 is for (RLL = I head [U]; I; I = E [I] .nxt) { 34 is IF (E [I] .to =! FA [U]) { 35 FA [E [I] .to] = U; 36 DFS1 ( E [I] .to); 37 [ size [U] + =size [E [I] .to]; 38 is } 39 } 40 } 41 is 42 is inline void DFS2 (U LL) { // according to the severity of the number of child nodes edge division number, ensure that only a point in a chain. Usually only the heavy side and light side less than. 43 is LL T = 0 ; // Top i.e. the point where the heavy edges for this vertex 44 is IF Top [U] = (Top [U]!) U; 45 for (RLL head I = [U]; I; I = E [I] .nxt) { 46 is IF (E [I] .to FA = [U] && size [E [I] .to]> T) T =! E [I] .to; 47 } 48 IF (T) { 49 Top [T] = Top [U]; 50 DFS2 (T); 51 is } 52 is for (RLL head I = [U]; I; I = E [I] .nxt) { 53 is IF (E [I] .to FA = [U] && E [I] .to =!! T) DFS2 (E [I] .to); 54 is } 55 } 56 is 57 is inline LCA LL (LL X, Y LL) { // when the two points are located on a heavy chain that is the same operation is ended. Otherwise, skip to the depth where the depth of the point of the heavy chain of a point, the position of the point of the shallow depth at the end of the operation is also desired LCA 58 the while (Top [X]! = Top [Y]) { 59 IF (D [Top [X]] < D [Top [Y]]) the swap (X, Y); 60 X = FA [Top [X]]; 61 is } 62 is IF (D [X]> D [Y]) the swap (X, Y); 63 is return X; 64 } 65 66 int main(){ 67 n=read(),m=read(),s=read(); 68 For(i,1,n-1) {x=read(),y=read(),add(x,y),add(y,x);} 69 dfs1(s),dfs2(s); 70 For(i,1,m){x=read(),y=read(),printf("%lld\n",lca(x,y));} 71 return 0; 72 }
LCA template tree section seeking
Guess you like
Origin www.cnblogs.com/wi1d3on/p/11330922.html
Recommended
Ranking