【poj 1330】 Nearest Common Ancestors

来源:互联网 发布:淘宝买快排会查下来吗 编辑:程序博客网 时间:2024/06/15 03:45

题意:

首先输入一个t,表示数据组数,下面的每组数据的第一行,为n,表示有n个点,接下来是n-1条a b关系,表示a是b的父亲,接下来1行两个数,表示求这两个数的最近公共祖先。

思路:

先找到树的根,再求两点的lca就好了。

代码:

#include <iostream>#include <algorithm>#include <cstdio>using namespace std;const int  maxn = 20010;int n, t;int _first[maxn], _next[maxn], _to[maxn], cnt, up[maxn][30], deep[maxn], du[maxn];void add(int a, int b){    _next[++cnt] = _first[a];    _first[a] = cnt;    _to[cnt] = b;}void dfs(int now){    for(int i = 1; i <= 25; i ++)        up[now][i] = up[up[now][i-1]][i-1];    for(int i = _first[now]; i; i = _next[i]){        if(_to[i] != up[now][0]){            up[_to[i]][0] = now;            deep[_to[i]] = deep[now] + 1;            dfs(_to[i]);        }    }}int lca(int x, int y){    if(x == y) return x;    if(deep[x] < deep[y]) swap(x, y);    if(deep[x] != deep[y])        for(int i = 25; i >= 0; i --)            if(deep[up[x][i]] >= deep[y]) x = up[x][i];    if(x == y) return x;    for(int i = 25; i >= 0; i --)        if(up[x][i] != up[y][i]) x = up[x][i], y = up[y][i];    return up[x][0];}int main(){    scanf("%d", &t);    while(t --){        int a, b;        cnt = 0;        for(int i = 1; i <= n; i ++) _first[i] = 0, deep[i] = 0, du[i] = 0;        scanf("%d", &n);        for(int i = 1; i < n; i ++){            scanf("%d%d", &a, &b);            add(a, b), du[b] ++;        }        for(int i = 1; i <= n; i ++)            if(du[i] == 0){                deep[i] = 1, dfs(i);                break;            }        scanf("%d%d", &a, &b);        printf("%d\n", lca(a, b));    }    return 0;}
1 0
原创粉丝点击