倍增求LCA

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<algorithm>
 4 #include<cmath>
 5 #include<cstring>
 6 #include<queue>
 7 #include<map> 
 8 #include<string>
 9 #include<ctime>
10 #define ll long long
11 #define inf 1010580540
12 #define DB double
13 using namespace std;
14 inline int read()
15 {
16     int x=0,w=1;char ch=0;
17     while(!isdigit(ch)){if(ch=='-') w=-1;ch=getchar();}
18     while(isdigit(ch)) x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
19     return x*w;
20 }
21 int buf[60];
22 void write(int x)
23 {
24     if(x<0) putchar('-'),x=-x;
25     buf[0]=0;
26     while(x) buf[++buf[0]]=x%10,x/=10;
27     if(!buf[0]) buf[0]=1,buf[1]=0;
28     while(buf[0]) putchar('0'+buf[buf[0]--]);
29 }
30 int n,m,h[1000000],s,tot;
31 struct po{int u,v,last;}a[1000000];
32 int f[500002][30],dep[500005];
33 void add(int u,int v)
34 {
35     tot++;a[tot].v=v;
36     a[tot].last=h[u];h[u]=tot;
37     a[tot].u=u;
38 }
39 void dfs(int u)
40 {
41     for(int i=h[u];i;i=a[i].last)
42     {
43         int to=a[i].v;
44         if(dep[to]==0)
45         {
46           dep[to]=dep[u]+1;
47           f[to][0]=u;
48           dfs(to);    
49         }
50     } 
51 }
52 void YU()
53 {
54     for(int j=1;(1<<j)<=n;j++)
55      for(int i=1;i<=n;i++)
56       f[i][j]=f[f[i][j-1]][j-1];
57 } 
58 int lca(int x,int y)
59 {
60     if(dep[x]<dep[y]) swap(x,y);
61     int h=dep[x]-dep[y];
62     for(int j=0;j<=20;j++)
63      if((1<<j)&h) x=f[x][j];
64     for(int j=20;j>=0;j--)
65      if(f[x][j]!=f[y][j]) x=f[x][j],y=f[y][j];
66     //cout<<x<<" "<<y<<endl;
67     if(x==y) return x;
68     else return f[x][0];
69 }
70 int main()
71 { 
72     n=read(),m=read(),s=read();
73     for(int i=1;i<=n-1;i++)
74     {
75       int x,y;x=read();y=read();
76       add(x,y);add(y,x);    
77     }
78     dep[s]=1;
79     dfs(s);YU();
80     for(int i=1;i<=m;i++)
81     {
82       int x,y,z;
83       x=read(),y=read();
84       z=lca(x,y);
85       write(z);
86       putchar('
');    
87     }
88     return 0;
89 } 
View Code

只是板子。

然后滚回去学习吧。

bye?bye?

原文地址:https://www.cnblogs.com/adelalove/p/8491818.html