【LCA】倍增模板
阿新 • • 發佈:2019-01-06
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
const int maxn = 500005;
int n, m, s;
int cnt = 0;
int head[maxn], deep[maxn], p[maxn][21];
int v[maxn * 2], next[maxn * 2];
void add(int x , int y)
{
v[cnt] = y;
next[cnt] = head[x];
head[x] = cnt++;
}
void dfs(int u, int fa)
{
deep[u] = deep[fa] + 1;
p[u][0] = fa;
for(int i = 1; (1 << i) <= deep[u]; i++)
p[u][i] = p[p[u][i-1]][i-1];
for(int i = head[u]; i != -1; i = next[i])
{
if(v[i] != fa)
dfs(v[i], u);
}
}
int lca(int a, int b)
{
if(deep[a] > deep[b])
swap(a, b);
for(int i = 20 ; i >= 0; i--)
if(deep[a] <= deep[b] - (1 << i))
b = p[b][i];
if(a == b)
return a;
for(int i = 20; i >= 0; i--)
{
if(p[a][i] == p[b][i])
continue;
else
a = p[a][i];
b = p[b][i];
}
return p[a][0];
}
int main()
{
memset(head,-1,sizeof(head));
int a, b;
scanf("%d%d%d", &n, &m, &s);
for(int i = 1; i < n; i++)
{
scanf("%d%d", &a, &b);
add(a, b);
add(b, a);
}
dfs(s, 0);
for(int i = 1; i <= m; i++)
{
scanf("%d%d", &a, &b);
printf("%d\n", lca(a,b));
}
return 0;
}
#include<iostream>
#include<cstring>
using namespace std;
const int maxn = 500005;
int n, m, s;
int cnt = 0;
int head[maxn], deep[maxn], p[maxn][21];
int v[maxn * 2], next[maxn * 2];
void add(int x , int y)
{
v[cnt] = y;
next[cnt] = head[x];
head[x] = cnt++;
}
void dfs(int u, int fa)
{
deep[u] = deep[fa] + 1;
p[u][0] = fa;
for(int i = 1; (1 << i) <= deep[u]; i++)
p[u][i] = p[p[u][i-1]][i-1];
for(int i = head[u]; i != -1; i = next[i])
{
if(v[i] != fa)
dfs(v[i], u);
}
}
int lca(int a, int b)
{
if(deep[a] > deep[b])
swap(a, b);
for(int i = 20 ; i >= 0; i--)
if(deep[a] <= deep[b] - (1 << i))
b = p[b][i];
if(a == b)
return a;
for(int i = 20; i >= 0; i--)
{
if(p[a][i] == p[b][i])
continue;
else
a = p[a][i];
}
return p[a][0];
}
int main()
{
memset(head,-1,sizeof(head));
int a, b;
scanf("%d%d%d", &n, &m, &s);
for(int i = 1; i < n; i++)
{
scanf("%d%d", &a, &b);
add(a, b);
add(b, a);
}
dfs(s, 0);
for(int i = 1; i <= m; i++)
{
scanf("%d%d", &a, &b);
printf("%d\n", lca(a,b));
}
return 0;
}