POJ 1330 Nearest Common Ancestors (LCA,倍增算法,在线算法)
2013-09-05 10:22
507 查看
/* *********************************************** Author :kuangbin Created Time :2013-9-5 9:45:17 File Name :F:\2013ACM练习\专题学习\LCA\POJ1330_3.cpp ************************************************ */ #include <stdio.h> #include <string.h> #include <iostream> #include <algorithm> #include <vector> #include <queue> #include <set> #include <map> #include <string> #include <math.h> #include <stdlib.h> #include <time.h> using namespace std; /* * POJ 1330 * LCA 在线算法 */ const int MAXN = 10010; const int DEG = 20; struct Edge { int to,next; }edge[MAXN*2]; int head[MAXN],tot; void addedge(int u,int v) { edge[tot].to = v; edge[tot].next = head[u]; head[u] = tot++; } void init() { tot = 0; memset(head,-1,sizeof(head)); } int fa[MAXN][DEG];//fa[i][j]表示结点i的第2^j个祖先 int deg[MAXN];//深度数组 void BFS(int root) { queue<int>que; deg[root] = 0; fa[root][0] = root; que.push(root); while(!que.empty()) { int tmp = que.front(); que.pop(); for(int i = 1;i < DEG;i++) fa[tmp][i] = fa[fa[tmp][i-1]][i-1]; for(int i = head[tmp]; i != -1;i = edge[i].next) { int v = edge[i].to; if(v == fa[tmp][0])continue; deg[v] = deg[tmp] + 1; fa[v][0] = tmp; que.push(v); } } } int LCA(int u,int v) { if(deg[u] > deg[v])swap(u,v); int hu = deg[u], hv = deg[v]; int tu = u, tv = v; for(int det = hv-hu, i = 0; det ;det>>=1, i++) if(det&1) tv = fa[tv][i]; if(tu == tv)return tu; for(int i = DEG-1; i >= 0; i--) { if(fa[tu][i] == fa[tv][i]) continue; tu = fa[tu][i]; tv = fa[tv][i]; } return fa[tu][0]; } bool flag[MAXN]; int main() { //freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); int T; int n; int u,v; scanf("%d",&T); while(T--) { scanf("%d",&n); init(); memset(flag,false,sizeof(flag)); for(int i = 1;i < n;i++) { scanf("%d%d",&u,&v); addedge(u,v); addedge(v,u); flag[v] = true; } int root; for(int i = 1;i <= n;i++) if(!flag[i]) { root = i; break; } BFS(root); scanf("%d%d",&u,&v); printf("%d\n",LCA(u,v)); } return 0; }
相关文章推荐
- POJ 1330 Nearest Common Ancestors(在线倍增LCA)
- 【POJ】1330 Nearest Common Ancestors 在线LCA,倍增思想
- POJ 1330 Nearest Common Ancestors 倍增法求LCA
- POJ 1330 Nearest Common Ancestors(tarjan , 倍增法求LCA) - from lanshui_Yang
- POJ 1330 Nearest Common Ancestors(LCA 可以用ST算法 NlogN 或者简单搜索)
- POJ - 1330 Nearest Common Ancestors(LCA最近公共祖先 朴素算法&倍增法)
- 【LCA倍增】POJ1330-Nearest Common Ancestors
- 【POJ1330】Nearest Common Ancestors-LCA算法
- [省选前题目整理][POJ 1330]Nearest Common Ancestors(倍增法求LCA)
- Poj-1330-Nearest Common Ancestors-倍增LCA
- POJ1330 Nearest Common Ancestors【最近公共祖先】【Tarjan-LCA算法】
- 倍增LCA poj1330 Nearest Common Ancestors
- POJ 1330 Nearest Common Ancestors(tarjan LCA 算法)
- POJ:1330-Nearest Common Ancestors(LCA在线、离线、优化算法)
- POJ 1330 Nearest Common Ancestors(LCA 在线算法)
- poj 1330 Nearest Common Ancestors(LCA)
- POJ 1330 Nearest Common Ancestors (最近公共祖先LCA + 详解博客)
- poj 1330 Nearest Common Ancestors(LCA模板)
- POJ-1330 Nearest Common Ancestors【LCA】
- [POJ1330]Nearest Common Ancestors(LCA, 离线tarjan)