您的位置:首页 > 其它

POJ 1330 Nearest Common Ancestors LCA

2014-10-06 19:51 423 查看
Nearest Common Ancestors

Time Limit: 1000MSMemory Limit: 10000K
Total Submissions: 18969Accepted: 10043
Description

A rooted tree is a well-known data structure in computer science and engineering. An example is shown below:




In the figure, each node is labeled with an integer from {1, 2,...,16}. Node 8 is the root of the tree. Node x is an ancestor of node y if node x is in the path between the root and node y. For example, node 4 is an ancestor of node 16. Node 10 is also an ancestor
of node 16. As a matter of fact, nodes 8, 4, 10, and 16 are the ancestors of node 16. Remember that a node is an ancestor of itself. Nodes 8, 4, 6, and 7 are the ancestors of node 7. A node x is called a common ancestor of two different nodes y and z if node
x is an ancestor of node y and an ancestor of node z. Thus, nodes 8 and 4 are the common ancestors of nodes 16 and 7. A node x is called the nearest common ancestor of nodes y and z if x is a common ancestor of y and z and nearest to y and z among their common
ancestors. Hence, the nearest common ancestor of nodes 16 and 7 is node 4. Node 4 is nearer to nodes 16 and 7 than node 8 is.

For other examples, the nearest common ancestor of nodes 2 and 3 is node 10, the nearest common ancestor of nodes 6 and 13 is node 8, and the nearest common ancestor of nodes 4 and 12 is node 4. In the last example, if y is an ancestor of z, then the nearest
common ancestor of y and z is y.

Write a program that finds the nearest common ancestor of two distinct nodes in a tree.

Input

The input consists of T test cases. The number of test cases (T) is given in the first line of the input file. Each test case starts with a line containing an integer N , the number of nodes in a tree, 2<=N<=10,000. The nodes are labeled with integers 1, 2,...,
N. Each of the next N -1 lines contains a pair of integers that represent an edge --the first integer is the parent node of the second integer. Note that a tree with N nodes has exactly N - 1 edges. The last line of each test case contains two distinct integers
whose nearest common ancestor is to be computed.
Output

Print exactly one line for each test case. The line should contain the integer that is the nearest common ancestor.
Sample Input
2
16
1 14
8 5
10 16
5 9
4 6
8 4
4 10
1 13
6 15
10 11
6 7
10 2
16 3
8 1
16 12
16 7
5
2 3
3 4
3 1
1 5
3 5

Sample Output
4
3

Source
Taejon 2002

离线算法
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <bitset>

using namespace std;

#define PB push_back
#define MP make_pair
#define REP(i,n) for(int i=0;i<(n);++i)
#define FOR(i,l,h) for(int i=(l);i<=(h);++i)
#define DWN(i,h,l) for(int i=(h);i>=(l);--i)
#define CLR(vis,pos) memset(vis,pos,sizeof(vis))
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define LINF 1000000000000000000LL
#define eps 1e-8

typedef long long ll;

const int maxn=1e4+10;

int f[maxn];
int r[maxn];
int indegree[maxn];//保存每个节点的入度
int vis[maxn];
vector<int> tree[maxn];
vector<int> qes[maxn];
int ancestor[maxn];
int n;

void init(){
    FOR(i,1,n){
        r[i]=1;
        f[i]=i;
        vis[i]=0;
        indegree[i]=0;
        ancestor[i]=0;
        tree[i].clear();
        qes[i].clear();
    }
}

int find(int u){
    if(f[u]==u)  return u;
    else         return f[u]=find(f[u]);
}//查找函数,并压缩路径

int Union(int x,int y){
    int a=find(x);
    int b=find(y);
    if(a==b) return 0;
    else{
        if(r[a]<=r[b]){
            f[a]=b;
            r[b]+=r[a];
        }
        else{
            f[b]=a;
            r[a]+=r[b];
        }
    }
    return 1;
}//合并函数,如果属于同一分支则返回0,成功合并返回1

void LCA(int u){
    ancestor[u]=u;
    REP(i,tree[u].size()){
        LCA(tree[u][i]);
        Union(u,tree[u][i]);
        ancestor[find(u)]=u;
    }
    vis[u]=1;
    REP(i,qes[u].size()){
        if(vis[qes[u][i]]){
            printf("%d\n",ancestor[find(qes[u][i])]);
            return;
        }
    }
}

int main()
{
    int _;
    cin>>_;
    REP(cas,_){
       cin>>n;
       init();
       int u,v;
       REP(i,n-1){
           scanf("%d%d",&u,&v);
           tree[u].PB(v);
           indegree[v]++;
       }
       scanf("%d%d",&u,&v);//这里可以输入多组询问
       //相当于询问两次
       qes[u].PB(v);
       qes[v].PB(u);
       FOR(i,1,n){
           if(!indegree[i]){ //寻找根节点
              LCA(i);
              break;
           }
       }
    }
    return 0;
}


在线算法
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <bitset>

using namespace std;

#define PB push_back
#define MP make_pair
#define REP(i,n) for(int i=0;i<(n);++i)
#define FOR(i,l,h) for(int i=(l);i<=(h);++i)
#define DWN(i,h,l) for(int i=(h);i>=(l);--i)
#define CLR(vis,pos) memset(vis,pos,sizeof(vis))
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define LINF 1000000000000000000LL
#define eps 1e-8

typedef long long ll;

const int maxn=1e4+10;
const int DEG=20;

struct node{
    int to;
    int next;
}e[maxn*2];

int head[maxn],edge;

void init(){
    CLR(head,-1);
    edge=0;
}

void addedge(int u,int v){
    e[edge].to=v;
    e[edge].next=head[u];
    head[u]=edge++;
}

int f[maxn][DEG];//f[i][j]表示结点i的第2^j个祖先
int deg[maxn];//深度数组

void bfs(int root){
    queue<int> q;
    deg[root]=0;
    f[root][0]=root;
    q.push(root);
    while(!q.empty()){
        int tmp=q.front();
        q.pop();
        FOR(i,1,DEG-1){
            f[tmp][i]=f[f[tmp][i-1]][i-1];
        }
        for(int i=head[tmp];~i;i=e[i].next){
            int v=e[i].to;
            if(v==f[tmp][0]) continue;
            deg[v]=deg[tmp]+1;
            f[v][0]=tmp;
            q.push(v);
        }
    }
}

int LCA(int u,int v)
{
    if(deg[u]>deg[v])swap(u,v);
    int hu=deg[u],hv=deg[v];
    int tu = u, tv = v;
    for(int det=hv-hu,i=0 ; det ; det>>=1,i++)
          if(det&1)
            tv=f[tv][i];
     if(tu==tv) return tu;
     for(int i=DEG-1;i>=0;i--)
     {
         if(f[tu][i]==f[tv][i])
             continue;
          tu=f[tu][i];
         tv=f[tv][i];
     }
      return f[tu][0];
}

bool flag[maxn];

int main()
{
    int _;
    int n;
    cin>>_;
    REP(cas,_){
        cin>>n;
        init();
        CLR(flag,false);
        int u,v;
        REP(i,n-1){
            scanf("%d%d",&u,&v);
            addedge(u,v);
            addedge(v,u);
            flag[v]=true;
        }
        int root;
        FOR(i,1,n){
            if(!flag[i]){
                root=i;
                break;
            }
        }
        bfs(root);
        scanf("%d%d",&u,&v);
        printf("%d\n",LCA(u,v));
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: