题目链接:点击进入
题目
思路
倍增求lca( 最近公共祖先 )
代码
// Problem: P3379 【模板】最近公共祖先(LCA)
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P3379
// Memory Limit: 500 MB
// Time Limit: 1500 ms
//
// Powered by CP Editor (https://cpeditor.org)
//#pragma GCC optimize(3)//O3
//#pragma GCC optimize(2)//O2
#include<iostream>
#include<string>
#include<map>
#include<set>
//#include<unordered_map>
#include<queue>
#include<cstdio>
#include<vector>
#include<cstring>
#include<stack>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<fstream>
#define X first
#define Y second
#define base 233
#define pb push_back
#define INF 0x3f3f3f3f3f3f3f3f
#define pii pair<int,int>
#define lowbit(x) x & -x
#define inf 0x3f3f3f3f
//#define int long long
//#define double long double
//#define rep(i,x,y) for(register int i = x; i <= y;++i)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const double pai=acos(-1.0);
const int maxn=1e6+10;
const int mod=1e9+7;
const double eps=1e-9;
const int N=5e3+10;
/*--------------------------------------------*/
inline int read()
{
int k = 0, f = 1 ;
char c = getchar() ;
while(!isdigit(c)){if(c == '-') f = -1 ;c = getchar() ;}
while(isdigit(c)) k = (k << 1) + (k << 3) + c - 48 ,c = getchar() ;
return k * f ;
}
/*--------------------------------------------*/
int n,m,s,head[maxn],tot;
struct node
{
int to;
int next;
}edge[maxn];
int deep[maxn],lg[maxn],pre[maxn][30];
void init()
{
memset(head,-1,sizeof(head));
memset(deep,0,sizeof(deep));
memset(lg,0,sizeof(lg));
memset(pre,0,sizeof(pre));
tot=0;
}
void add(int u,int v)
{
edge[tot].to=v;
edge[tot].next=head[u];
head[u]=tot++;
}
void dfs(int pos,int fa)
{
pre[pos][0]=fa;
deep[pos]=deep[fa]+1;
for(int i=1;i<=lg[deep[pos]];i++)
pre[pos][i]=pre[pre[pos][i-1]][i-1];
for(int i=head[pos];i!=-1;i=edge[i].next)
if(edge[i].to!=fa)
dfs(edge[i].to,pos);
}
int lca(int x,int y)
{
if(deep[x]<deep[y]) swap(x,y);
while(deep[x]>deep[y])
x=pre[x][lg[deep[x]-deep[y]]-1];
if(x==y) return x;
for(int i=lg[deep[x]]-1;i>=0;i--)
if(pre[x][i]!=pre[y][i])
x=pre[x][i],y=pre[y][i];
return pre[x][0];
}
int main()
{
// ios::sync_with_stdio(false);
// cin.tie(0);cout.tie(0);
init();
cin>>n>>m>>s;
for(int i=1;i<n;i++)
{
int x,y;
cin>>x>>y;
add(x,y);
add(y,x);
}
for(int i=1;i<=n;i++)
lg[i]=lg[i>>1]+1;
dfs(s,0);
while(m--)
{
int x,y;
cin>>x>>y;
cout<<lca(x,y)<<endl;
}
return 0;
}