LCA

倍增

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
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
using namespace std;
#define R register
int n,m,tmp1,tmp2,dep[500001];
int fa[500001][21],s;
bool vis[500001];
vector<int>ma[500001];
void read(int & x)
{
char c=getchar();x=0;
while(c<'0'||c>'9')c=getchar();
while(c>='0'&&c<='9')x=x*10+c-48,c=getchar();
}
void dfs(int now,int d)
{
vis[now]=1;dep[now]=d;
R int siz=ma[now].size();
for(int i=0;i<siz;++i)
if(!vis[ma[now][i]])dfs(ma[now][i],d+1),fa[ma[now][i]][0]=now;
}
void bz(){for(int j=1;j<20;++j)for(int i=1;i<=n;++i)fa[i][j]=fa[fa[i][j-1]][j-1];}
int lca(int u,int v)
{
if(dep[u]<dep[v])swap(u,v);
R int d=dep[u]-dep[v];
for(int i=19;i>=0;--i)if((1<<i)&d)u=fa[u][i];
if(u==v)return v;
for(int i=19;i>=0;--i)if(fa[u][i]!=fa[v][i])u=fa[u][i],v=fa[v][i];
return fa[u][0];
}
int main()
{
scanf("%d%d%d",&n,&m,&s);//s是树根
for(int i=1;i<n;++i)
{
scanf("%d%d",&tmp1,&tmp2);
ma[tmp1].push_back(tmp2);
ma[tmp2].push_back(tmp1);
}
dfs(s,1);bz();
for(int i=1;i<=m;++i)
{
scanf("%d%d",&tmp1,&tmp2);
printf("%d\n",lca(tmp1,tmp2));
}
return 0;
}

树链剖分

待我学完树链剖分来补这个坑..

显示 Gitment 评论