1. 程式人生 > >Nearest Common Ancestors(POJ-1330)(LCA轉RMQ線上演算法)

Nearest Common Ancestors(POJ-1330)(LCA轉RMQ線上演算法)

Nearest Common Ancestors
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 29996 Accepted: 15332

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
題目大意: 這個題目的意思就是讀入有n個頂點,n-1條邊的樹,在給出一個查詢,求得這兩個頂點的的最小公共祖先。
   最小公共祖先就是距離兩個點最近的父節點。 題目思路: 最基礎的LCA模板題只有一個查詢,最近學了LCA轉RMQ線上演算法就直接寫了,雖然錯了好多次。。                    但是這個最容易想到的就是直接從底層向上找到同一個父節點為止,這個寫了也給貼出來啦。 最容易想到的寫法:

程式碼1:

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
#include <vector>
using namespace std;
typedef long long LL;
const int N=10099;
int dpth[N]; //儲存每個節點的深度
int per[N]; // 儲存每個節點的祖先
vector <int> a[N];
void dfs(int x,int d)
{
    dpth[x]=d;
    for(int i=0; i<a[x].size(); i++)
    {
        dfs(a[x][i],d+1);
    }
}
int main()
{
    int n,t;
    scanf("%d",&t);
    while(t--)
    {
        memset(per,-1,sizeof(per)); //將祖先初始化為-1
        scanf("%d",&n);
        for(int i=1; i<=n; i++) a[i].clear(); //將vector陣列清空
        int x,y;
        for(int i=1; i<=n-1; i++)
        {
            scanf("%d%d",&x,&y);
            a[x].push_back(y); //將x->y存入vector陣列
            per[y]=x;
        }
        int s=1;
        while(per[s]>=1) //找到樹的根節點
            s++;
        dfs(s,0);
        scanf("%d%d",&x,&y);
        //一層一層的向上找,直到找到共同祖先跳出
        while(x!=y)
        {
            if(dpth[x]>dpth[y]) x=per[x];
            else y=per[y];
        }
        printf("%d\n",x);
    }
    return 0;
}
LCA寫法 :我覺得比較麻煩,要建立好多陣列。。 貼個看著不錯的部落格的連結,不懂LCA的可以去看看。

程式碼2:

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
#include <vector>
using namespace std;
typedef long long LL;
const int N=10099;
int dp[N<<1][30],dpth[N<<1];    // dp陣列用RMQ計算深度的最小值下標 ,dpth陣列儲存深度
int first[N],vis[N<<1],k,per[N];//first陣列標記節點第一次出現,vis陣列儲存遍歷的順序,per陣列儲存祖先
bool book[N];                   //book陣列用來標記這個點進入過沒有
vector <int> a[N];
//最小深度的下標
void ST(int n)
{
    for(int i=1;i<=n;i++)
        dp[i][0]=i;
    for(int j=1;(1<<j)<=n;j++)
    {
        for(int i=1 ; i+(1<<j)-1<=n ; i++)
        {
            int a=dp[i][j-1];
            int b=dp[i+(1<<(j-1))][j-1];
            if(dpth[a]<=dpth[b]) dp[i][j]=a;
            else dp[i][j]=b;
        }
    }
}
int RMQ(int l,int r)
{
    int k=log(r-l+1.0)/log(2.0);
    int a=dp[l][k];
    int b=dp[r-(1<<k)+1][k];
    if(dpth[a]<=dpth[b]) return a;
    else return b;
}
int LCA(int u,int v)
{
    //找出這兩個數在first陣列中的值,排列成 x<y
    int x=first[u];
    int y=first[v];
    if(x>y) swap(x,y);
    int res=RMQ(x,y);
    return vis[res]; //返回在遍歷陣列中對應的節點
}
void dfs(int x,int d)
{
    book[x]=true;
    k++;
    first[x]=k;
    dpth[k]=d;
    vis[k]=x;
    for(int i=0; i < a[x].size() ;i++)
    {
        if(!book[a[x][i]])
        {
            dfs(a[x][i],d+1);
            k++;
            dpth[k]=d;
            vis[k]=x;
        }
    }
}
int main()
{
    int n,t;
    scanf("%d",&t);
    while(t--)
    {
        //初始化
        memset(book,false,sizeof(book));
        memset(vis,0,sizeof(vis));
        memset(per,-1,sizeof(per));
        k=0;
        scanf("%d",&n);
        for(int i=1; i<=n; i++) a[i].clear();
        int x,y;
        for(int i=1; i<=n-1; i++)
        {
            scanf("%d%d",&x,&y);
            a[x].push_back(y);
            per[y]=x;
        }
        int i;
        for(i=1;i<=n-1;i++) if(per[i]==-1) break; //找根節點
        dfs(i,0);
        ST(2*n-1); //遍歷n個節點剛好2n-1
        scanf("%d%d",&x,&y);
        int ans=LCA(x,y);
        printf("%d\n",ans);
    }
    return 0;
}