标签:
题目链接:http://poj.org/problem?id=1330
题目大意十分明了简单,就是给定一棵树,求某两个子节点的最近公共祖先,如果尚不清楚LCA的同学,可以左转百度等进行学习。
稍微需要注意的是,建树顺序需要按照题目给定的顺序进行,也就是说根被设定成第一个给出的结点,如样例2。
此题网上题解颇多,但是多是使用的邻接表存图,于是我这里采用了边表,不过实质上Tarjan的部分思想都是一样的,均利用了并查集。
AC代码:
#include <cstdio> #include <cstring> #include <iostream> using namespace std; typedef long long LL; #define MAXN 10010 int t, n; int headEdge[MAXN], headQuery[MAXN], father[MAXN]; int totEdge, totQuery; struct Edge { int to, next; } edge[MAXN << 1]; struct Node { int to, next, num; } Query[MAXN << 1]; struct node { int u, v, lca; } input[MAXN]; void init() { totEdge = totQuery = 0; memset(headEdge, -1, sizeof(headEdge)); memset(headQuery, -1, sizeof(headQuery)); memset(father, -1, sizeof(father)); } void addEdge(int from, int to) { edge[totEdge].to = to; edge[totEdge].next = headEdge[from]; headEdge[from] = totEdge++; } void addQuery(int from, int to, int x) { Query[totQuery].to = to; Query[totQuery].num = x; Query[totQuery].next = headQuery[from]; headQuery[from] = totQuery++; } int find_set(int x) { if(father[x] == x) return x; else return father[x] = find_set(father[x]); } void union_set(int x, int y) { x = find_set(x); y = find_set(y); if(x != y) father[y] = x; } void Tarjan(int u) { father[u] = u; for(int i = headEdge[u]; i != -1; i = edge[i].next) { int v = edge[i].to; if(father[v] != -1) continue; Tarjan(v); union_set(u, v); } for(int i = headQuery[u]; i != -1; i = Query[i].next) { int v = Query[i].to; if(father[v] == -1) continue; input[Query[i].num].lca = find_set(v); } } int main() { scanf("%d", &t); while(t--) { init(); scanf("%d", &n); int a, b; int root; for(int i = 0; i < n - 1; i++) { scanf("%d%d", &a, &b); if (i == 0) root = a;// 记录一下根的位置 addEdge(a, b); addEdge(b, a); } //如果需要多个查询,i的循环可以开到m次即可 for(int i = 0; i < 1; i++) { scanf("%d%d", &a, &b); input[i].u = a, input[i].v = b; addQuery(a, b, i); addQuery(b, a, i); } Tarjan(root); printf("%d\n", input[0].lca); } return 0; }
POJ 1330 最近公共祖先LCA(Tarjan离线做法)
标签:
原文地址:http://www.cnblogs.com/gaoxiang36999/p/4484207.html