poj 1330


LCA倍增,以前写过离线Tarjan,不多说


#include<map>
#include<string>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<ctime>
#include<cmath>
#include<iostream>
#include<algorithm>
const int MAXN = 10005 , logN = 15;

int n;
struct Edge{int v,next;}edge[MAXN<<1] = {0};int el = 0;
int head[MAXN] = {0}, fa[MAXN][logN] = {0} , dep[MAXN] = {0};
bool hash[MAXN] = {0};

void newedge(int u,int v)
{
    ++el; edge[el].v = v;
    edge[el].next = head[u],head[u] = el;
}
void build(int a)
{
    dep[a] = dep[fa[a][0]] + 1;
    for(int i = head[a]; i; i = edge[i].next)
    {
        int p = edge[i].v;
        if(p == fa[a][0])continue;
        fa[p][0] = a; build(p);
    }
}
void prelca()
{
    for(int j = 1 ; j < logN; j++)
      for(int i = 1; i <= n ; i++)
        fa[i][j] = fa[fa[i][j-1]][j-1];
}
int getLCA(int u,int v)
{
    if(dep[u] > dep[v])std::swap(u,v);

    for(int i = logN - 1; i >= 0 ; i--)
      if(dep[fa[v][i]] >= dep[u]) v = fa[v][i];
    if(u == v) return u;  

    for(int i = logN - 1; i >= 0 ; i--)
      if(fa[u][i] != fa[v][i])u = fa[u][i],v = fa[v][i];

    return fa[v][0];  
}
int main()
{
    int T;

#ifndef ONLINE_JUDGE
    freopen("poj1330.in","r",stdin);
    freopen("poj1330.out","w",stdout);
#endif

    scanf("%d",&T);

    while(T--)
    {
        el = 0;
        memset(head,0,sizeof(head));
        memset(hash,false,sizeof(hash));

        int a ,b , root;
        scanf("%d",&n);
        for(int i = 1 ; i < n; i++)
        {
            scanf("%d%d",&a,&b);
            newedge(a,b); hash[b] = true;
        }
        for(int i = 1; i <= n; i++)
          if(hash[i] == false){root = i;break;}
        fa[root][0] = 0;
        build(root); prelca();
        scanf("%d%d",&a,&b);
        printf("%d\n",getLCA(a,b));
    }

#ifndef ONLINE_JUDGE
    fclose(stdin);
    fclose(stdout);
#endif
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值