POJ 1330 Nearest Common Ancestors(LCA在线算法)
2016-09-13 10:19
337 查看
// // main.cpp // Richard // // Created by 邵金杰 on 16/9/13. // Copyright © 2016年 邵金杰. All rights reserved. // #include<iostream> #include<cstdio> #include<cstring> #include<cmath> using namespace std; const int maxn=10000+100; int first[maxn],ver[maxn*2],dep[maxn*2],head[maxn],vis[maxn],dp[maxn*2][16],in[maxn]; struct edge{ int v,next; }edge[maxn]; int tot; int n; int cnt; void intial(){ cnt=0,tot=0; memset(vis,0,sizeof(vis)); memset(head,-1,sizeof(head)); memset(dp,0,sizeof(dp)); memset(in,0,sizeof(in)); } void add_edge(int u,int v){ edge[cnt].v=v; edge[cnt].next=head[u]; head[u]=cnt++; } void dfs(int fa,int d) { vis[fa]=1; ver[++tot]=fa; first[fa]=tot; dep[tot]=d; for(int i=head[fa];i!=-1;i=edge[i].next){ int v=edge[i].v; if(!vis[v]) { dfs(v,d+1); ver[++tot]=fa; dep[tot]=d; } } } void ST(int N) { for(int i=1;i<=N;i++) dp[i][0]=i; for(int j=1;(1<<j)<=N;j++) { for(int i=1;i<=N;i++) { if(i+(1<<(j-1))<=N) { int a=dp[i][j-1],b=dp[i+(1<<(j-1))][j-1]; dp[i][j]=dep[a]<dep[b]?a:b; } } } } int RMQ(int x,int y) { int k=floor(log(y-x+1)/log(2)); int a=dp[x][k],b=dp[y-(1<<k)+1][k]; return dep[a]<dep[b]?a:b; } int LCA(int u,int v) { int x=first[u],y=first[v]; if(x>y) swap(x,y); int pos=RMQ(x,y); return ver[pos]; } int main() { int t; scanf("%d",&t); while(t--) { intial(); scanf("%d",&n); int u,v; for(int i=0;i<n-1;i++) { scanf("%d%d",&u,&v); in[v]++; add_edge(u,v); } for(int i=1;i<=n;i++) { if(in[i]==0){ dfs(i,1); } } ST(2*n-1); scanf("%d%d",&u,&v); cout<<LCA(u,v)<<endl; } return 0; }
相关文章推荐
- POJ 1330 Nearest Common Ancestors
- [省选前题目整理][POJ 1330]Nearest Common Ancestors(倍增法求LCA)
- 【LCA倍增】POJ1330-Nearest Common Ancestors
- poj 1330 Nearest Common Ancestors
- 【POJ 1330】Nearest Common Ancestors(LCA_trajan)
- poj 1330 Nearest Common Ancestors
- POJ 1330 Nearest Common Ancestors (在线LCA转RMQ)
- 【POJ 1330】 Nearest Common Ancestors(LCA)
- 倍增LCA poj1330 Nearest Common Ancestors
- poj 1330 Nearest Common Ancestors(简单的树初探)
- poj 1330 Nearest Common Ancestors
- 【LCA|Tarjan】POJ-1330 Nearest Common Ancestors
- POJ 1330 Nearest Common Ancestors 笔记
- poj 1330 Nearest Common Ancestors
- POJ 1330:Nearest Common Ancestors
- [POJ 1330] Nearest Common Ancestors (倍增法)
- POJ 1330 Nearest Common Ancestors (LCA)
- poj 1330 Nearest Common Ancestors (最简单的LCA)
- 【POJ1330】Nearest Common Ancestors(LCA)
- poj 1330 Nearest Common Ancestors(LCA模板)