洛谷 3379 最近公共祖先(LCA 倍增)
题意分析
裸的板子题,但是注意这题n上限50w,我用的边表,所以要开到100w才能过,一开始re了两发,发现这个问题了。
代码总览
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#define nmax 1000100
#define demen 21
using namespace std;
int fa[nmax][demen],dis[nmax],head[nmax],dep[nmax];
int n,m,tot = 0;
struct node{
int to;
int next;
int w;
}edge[nmax];
void add(int u, int v){
edge[tot].to = v;
edge[tot].next = head[u];
head[u] = tot++;
}
void dfs(int rt,int f){
fa[rt][0] = f;
for(int i = 1;i<=20;++i){
fa[rt][i] = fa[fa[rt][i-1]][i-1];
}
for(int i = head[rt];i!=-1;i = edge[i].next){
int nxt = edge[i].to;
if(nxt != f){
dep[nxt] = dep[rt] + 1;
dfs(nxt,rt);
}
}
}
int lca(int x, int y){
int X = x,Y=y;
if(dep[x] < dep[y]) swap(x,y);
int dre = dep[x] - dep[y];
for(int i = 20;i>=0;--i){
if((1<<i) & dre)
x = fa[x][i];
}
if(x == y) return(x);
for(int i = 20;i>=0;--i){
if(fa[x][i] != fa[y][i]){
x = fa[x][i],y = fa[y][i];
}
}
return(fa[x][0]);
}
void init(){
memset(fa,0,sizeof fa);
memset(head,-1,sizeof head);
memset(dep,0,sizeof dep);
tot = 0;
}
int main()
{
init();
int n,m,k,u,v,w,root = 0;
scanf("%d %d %d",&n,&k,&root);
for(int i = 0;i<n-1;++i){
scanf("%d %d",&u,&v);
add(u,v);
add(v,u);
}
dep[root] = 1;
dfs(root,0);
int ans = 0;
for(int i = 0;i<k;++i){
scanf("%d %d",&u,&v);
printf("%d
",lca(u,v));
}
return 0;
}