链接:http://poj.org/problem?id=1330
题意:q次询问求两个点u,v的LCA
思路:LCA模板题,首先找一下树的根,然后dfs预处理求LCA(u,v)
AC代码:
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<set>
#include<string>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
typedef long long ll;
const int maxbit = ;
const int maxn = 1e4+;
vector<int> G[maxn];
int depth[maxn];
int fa[maxn][maxbit];
int Log[maxn];
int N;
void pre(){
Log[] = -;
Log[] = ,Log[] = ;
for(int i = ;i<maxn;i++) Log[i] = Log[i/] + ;
}
void dfs(int cur,int father){//dfs预处理
depth[cur] = depth[father] + ;//当前结点的深度为父亲结点+1
fa[cur][] = father;//更新当前结点的父亲结点
for(int j = ;(<<j)<=N;j++){//倍增更新当前结点的祖先
fa[cur][j] = fa[fa[cur][j-]][j-];
}
for(int i = ;i<G[cur].size() ;i++){
if(G[cur][i] != father) {//dfs遍历
dfs(G[cur][i],cur);
}
}
}
int LCA(int u,int v){
if(depth[u]<depth[v]) swap(u,v);
int dist = depth[u] - depth[v];//深度差
while(depth[u]!=depth[v]){//把较深的结点u倍增到与v高度相等
u = fa[u][Log[depth[u]-depth[v]]];
}
if(u == v) return u;//如果u倍增到v,说明v是u的LCA
for(int i = Log[depth[u]];i>=;i--){//否则两者同时向上倍增
if(fa[u][i]!=fa[v][i]){//如果向上倍增的祖先不同,说明是可以继续倍增
u = fa[u][i];//替换两个结点
v = fa[v][i];
}
}
return fa[u][];//最终结果为u v向上一层就是LCA
}
int main()
{
int t;
pre();
scanf("%d",&t);
while(t--){
scanf("%d",&N);
int root ;
int in[maxn];
for(int i = ;i<maxn;i++){
G[i].clear() ;
}
memset(in,,sizeof(in));
int u,v;
for(int i = ;i<N-;i++){
scanf("%d%d",&u,&v);
in[v] = ;
G[u].push_back(v);
G[v].push_back(u);
}
for(int i = ;i<=N;i++){//寻树的根结点
if(in[i] == ) {
root = i;
break;
}
}
dfs(root,);
scanf("%d%d",&u,&v);
int ans = LCA(u,v);
printf("%d\n",ans);
}
return ;
}