POJ 1330 Nearest Common Ancestors
题意:最近公共祖先的裸题
思路:LCA和ST我们已经很熟悉了,但是这里的f[i][j]却有相似却又不同的含义。f[i][j]表示i节点的第2j个父亲是多少
这个代码不是我的,转自 邝斌博客
/* ***********************************************
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 = ;
const int DEG = ; struct Edge
{
int to, next;
}edge[MAXN * ];
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 = ;
memset(head, -, sizeof(head));
}
int fa[MAXN][DEG];//fa[i][j]表示结点i的第2^j个祖先
int deg[MAXN];//深度数组 void BFS(int root)
{
queue<int>que;
deg[root] = ;
fa[root][] = root;
que.push(root);
while (!que.empty())
{
int tmp = que.front();
que.pop();
for (int i = ; i < DEG; i++)
fa[tmp][i] = fa[fa[tmp][i - ]][i - ];
for (int i = head[tmp]; i != -; i = edge[i].next)
{
int v = edge[i].to;
if (v == fa[tmp][])continue;
deg[v] = deg[tmp] + ;
fa[v][] = 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 = ; det; det >>= , i++)
if (det & )
tv = fa[tv][i];
if (tu == tv)return tu;
for (int i = DEG - ; i >= ; i--)
{
if (fa[tu][i] == fa[tv][i])
continue;
tu = fa[tu][i];
tv = fa[tv][i];
}
return fa[tu][];
}
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 = ; i < n; i++)
{
scanf("%d%d", &u, &v);
addedge(u, v);
addedge(v, u);
flag[v] = true;
}
int root;
for (int i = ; i <= n; i++)
if (!flag[i])
{
root = i;
break;
}
BFS(root);
scanf("%d%d", &u, &v);
printf("%d\n", LCA(u, v));
}
return ;
}