题目:http://poj.org/problem?id=1330
题意:给定一棵树,求两点的最近公共祖先
思路:刚学在线LCA,练练手
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;
const int N = 10010;
struct edge
{
int to, next;
}g[N*2];
int dp[20][N*2], deg[N];
int cnt, head[N];
int tot, dep[N*2], ver[N*2], fir[N];
bool vis[N];
void add_edge(int v, int u)
{
g[cnt].to = u, g[cnt].next = head[v], head[v] = cnt++;
}
void dfs(int v, int cur)
{
vis[v] = true, ver[++tot] = v, dep[tot] = cur, fir[v] = tot;
for(int i = head[v]; i != -1; i = g[i].next)
{
int u = g[i].to;
if(! vis[u])
{
dfs(u, cur + 1);
ver[++tot] = v, dep[tot] = cur;
}
}
}
void ST(int n)
{
for(int i = 1; i <= n; i++)
dp[0][i] = i;
for(int i = 1; (1<<i) <= n; i++)
for(int j = 1; j <= n - (1<<i) + 1; j++)
dp[i][j] = dep[dp[i-1][j]] < dep[dp[i-1][j+(1<<(i-1))]] ? dp[i-1][j] : dp[i-1][j+(1<<(i-1))];
}
int RMQ(int l, int r)
{
int k = log(r - l + 1) / log(2);
return dep[dp[k][l]] < dep[dp[k][r-(1<<k)+1]] ? dp[k][l] : dp[k][r-(1<<k)+1];
}
int LCA(int v, int u)
{
v = fir[v], u = fir[u];
if(v > u) swap(v, u);
int res = RMQ(v, u);
return ver[res];
}
int main()
{
int t, n, a, b;
scanf("%d", &t);
while(t--)
{
scanf("%d", &n);
cnt = tot = 0;
memset(head, -1, sizeof head);
memset(vis, 0, sizeof vis);
memset(deg, 0, sizeof deg);
for(int i = 0; i < n - 1; i++)
{
scanf("%d%d", &a, &b);
deg[b]++;
add_edge(a, b);
add_edge(b, a);
}
int root = -1;
for(int i = 1; i <= n; i++)
if(deg[i] == 0)
{
root = i; break;
}
dfs(root, 1);
ST(2 * n - 1);
scanf("%d%d", &a, &b);
printf("%d\n", LCA(a, b));
}
return 0;
}