POJ 1330 LCA入门题(Tarjan)
2013-10-20 11:50
543 查看
#include <cstdio> #include <iostream> #include <cstring> #include <vector> using namespace std; #define N 100010 #define bug(a) cout<<a<<"******"<<endl; int ok; int fa ,node ,vis ,anc ,ans; struct node { int to; int next; }edge[N<<2]; int head ,cnt; int que[2]; void init() { memset(head,-1,sizeof(head)); memset(node,0,sizeof(node)); memset(vis,0,sizeof(vis)); cnt = 0; } void add( int u , int v ) { edge[cnt].to = v; edge[cnt].next = head[u]; head[u] = cnt++; } int find(int x) { if(fa[x] != x) return fa[x] = find(fa[x]); return x; } void uni(int u,int v) { int x = find(u); int y = find(v); if( x != y ) fa[x] = y; } void LCA(int u) { int i,j,v; vis[u] = 1; for ( i = head[u] ; i != -1 ; i = edge[i].next ) { v = edge[i].to; if(vis[v]) continue; LCA(v); uni(u,v); anc[find(v)] = u; } if( u == que[0] && vis[que[1]] ) { ans = anc[find(que[1])]; return ; } if( u == que[1] && vis[que[0]]) { ans = anc[find(que[0])]; return ; } } int main() { int i,j,T,n,u,v; scanf("%d",&T); while(T--) { init(); scanf("%d",&n); for( i = 0 ; i <= n ; i ++ ) fa[i] = i ; for ( i = 0 ; i < n - 1 ; i ++ ) { scanf("%d%d",&u,&v); add(u,v); node[v] ++; } scanf("%d%d",&que[0],&que[1]); for ( i = 1 ; i <= n ; i ++ ) { if(!node[i]) { LCA(i); printf("%d\n",ans); break; } } } return 0 ; }
题目大意:
输入T组测试数据
输入N
接下来N-1行代表了一条边
输入A,B,其中A为B的父节点
第N行为询问,问该两点的最近公共祖先
相关文章推荐
- poj1330Nearest Common Ancestors(LCA小结)
- hdu 4674 边双连通缩点+倍增lca+麻烦的讨论 (2013多校联合)
- 【白话系列】最近公共祖先
- one piece_娜美_01
- poj 3694 Network LCA最小公共祖先
- Problem C
- HDU 2874 Connections between cities
- cf 324e Xenia and Tree
- 倍增法求最近公共祖先(LCA)的算法模板
- Range Minimum Query and Lowest Common Ancestor 区间最值查询和最近公共祖先问题
- CSU OJ:1427 谭松松的旅游计划(LCA)
- HDU6073 Phone Call
- hdu2586 How far away ? 【图论-Tarjan-Lca】
- poj3694 Network 【图论-Tarjan-Lca】
- noip模拟赛(一)魔法树
- 水题笔记:noip2013 货车运输 [LCA]
- Leetcode: Lowest Common Ancestor of a Binary Tree
- HDU 2586
- Tarjan算法(LCA)
- 最近公共祖先LCA问题(转)