poj 1330

来源:互联网 发布:自学凸优化 编辑:程序博客网 时间:2024/06/05 12:01

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;}
0 0
原创粉丝点击