标签:
The input consists of T test cases. The number of test cases (T) is given in the first line of the input file. Each test case starts with a line containing an integer N , the number of nodes in a tree, 2<=N<=10,000. The nodes are labeled with integers 1, 2,..., N. Each of the next N -1 lines contains a pair of integers that represent an edge --the first integer is the parent node of the second integer. Note that a tree with N nodes has exactly N - 1 edges. The last line of each test case contains two distinct integers whose nearest common ancestor is to be computed.
Print exactly one line for each test case. The line should contain the integer that is the nearest common ancestor.
3 5
Taejon 2002
题目大意:给你一棵树,有N个结点,N-1条边。最后询问距离树上两个点(u,v)最近的
公共祖先是多少。
比如上图:6和16的最近公共祖先就是4;14和1的最近公共祖先就是1。
思路:对于最近公共祖先LCA问题,最经典的离线算法是Tarjan-LCA算法。用链式前向
星存储图和询问,Head[]和Edges[]表示图(树),QHead[]和QEdges[]表示询问。集合
的操作用并查集实现。这道题里用了indegree[]数组来存储结点的入度,找到入度为0的
根结点root,调用LCA(root)。
Tarjan-LCA算法:
对于每一点u:
1.建立以u为代表元素的集合。
2.遍历与u相连的节点v,如果没有被访问过,对于v使用Tarjan-LCA算法,结束后,将
v的集合并入u的集合。
3.对于与节点u相关的询问(u,v),如果v被访问过,则结果就是v所在集合的所代表的元
素。
参考:ACM-ICPC程序设计系列——图论及应用
#include<iostream> #include<algorithm> #include<cstdio> #include<cstring> using namespace std; const int MAXN = 20020; struct EdgeNode { int to; int lca; int next; }; EdgeNode Edges[MAXN],QEdges[MAXN]; int father[MAXN],Head[MAXN],QHead[MAXN],indegree[MAXN]; int find(int x) { if(x != father[x]) father[x] = find(father[x]); return father[x]; } bool vis[MAXN]; void LCA(int u) { father[u] = u; vis[u] = true; for(int k = Head[u]; k != -1; k = Edges[k].next) { if(!vis[Edges[k].to]) { LCA(Edges[k].to); father[Edges[k].to] = u; } } for(int k = QHead[u]; k != -1; k = QEdges[k].next) { if(vis[QEdges[k].to]) { QEdges[k].lca = find(QEdges[k].to); QEdges[k^1].lca = QEdges[k].lca; } } } int main() { int T,N,u,v; scanf("%d",&T); while(T--) { memset(indegree,0,sizeof(indegree)); memset(father,0,sizeof(father)); memset(Head,-1,sizeof(Head)); memset(QHead,-1,sizeof(QHead)); memset(vis,false,sizeof(vis)); memset(Edges,0,sizeof(Edges)); memset(QEdges,0,sizeof(QEdges)); scanf("%d",&N); int id = 0; for(int i = 0; i < N-1; ++i) { scanf("%d%d",&u,&v); indegree[v]++; Edges[id].to = v; Edges[id].next = Head[u]; Head[u] = id++; Edges[id].to = u; Edges[id].next = Head[v]; Head[v] = id++; } int iq = 0; scanf("%d%d",&u,&v); QEdges[iq].to = v; QEdges[iq].next = QHead[u]; QHead[u] = iq++; QEdges[iq].to = u; QEdges[iq].next = QHead[v]; QHead[v] = iq++; int root; for(int i = 1; i <= N; ++i) { if(!indegree[i]) { root = i; break; } } LCA(root); printf("%d\n",QEdges[0].lca); } return 0; }
POJ1330 Nearest Common Ancestors【最近公共祖先】【Tarjan-LCA算法】
标签:
原文地址:http://blog.csdn.net/lianai911/article/details/42299921