【poj 1330】 Nearest Common Ancestors

题意:

首先输入一个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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值