C++

「LCA」最近公共祖先模版

前些日子学了LCA,觉得RMQ写法很玄学,而我喜欢玄学的东西,所以在我还没有完全写明白RMQ的LCA时,就先补充一下RMQ解决LCA的思路,但是不用RMQ那么玄学的维护方式,以POJ 1330举例子:

Nearest Common Ancestors

Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 31596 Accepted: 16106

Description

A rooted tree is a well-known data structure in computer science and engineering. An example is shown below:
img
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

题解

仔细看看,就一个询问诶,RMQ会更慢啊,还不如…

#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
#define N 20005

struct Edge{
    int u,v,next;
}edge[N];
int head[N],tot;
void addedge(int u,int v){
    tot++;
    edge[tot].u=u;
    edge[tot].v=v;
    edge[tot].next=head[u];
    head[u]=tot;
}
int first[N],occur[2*N],depth[2*N];
int m=0;

int T,n,a,b,u,v;
void dfs(int u,int dep){
    occur[++m]=u;
    depth[m]=dep;
    if(!first[u]) first[u]=m;
    for(int i=head[u];i;i=edge[i].next){
        dfs(edge[i].v,dep+1);
        occur[++m]=u;
        depth[m]=dep;
    }
}

void init(){
    tot=0,m=0,u=0,v=0;
    memset(head,0,sizeof(head));
    memset(first,0,sizeof(first));
    int in[N]={0};
    cin>>n;
    for(int i=1;i<n;i++){
        cin>>u>>v;
        addedge(u,v);
        in[v]=1;
    }
    for(int i=1;i<=n;i++){
        if(!in[i]){
            dfs(i,1);
            break;
        }
    }
    cin>>a>>b;
}

int main(){
    cin>>T;
    while(T--){
        init();
        // for(int i=1;i<=2*n-1;i++)cout<<occur[i]<<endl;
        int l=first[a],r=first[b];
        int t;
        if(l>r) t=l,l=r,r=t;
        int m=N,f;
        for(int i=l;i<=r;i++)
            if(depth[i]<=m) m=depth[i],f=i;
        cout<<occur[f]<<endl;
    }
    return 0;
}

看,一次dfs求欧拉序occur,深度depth,第一次出现的时间first

真的就这么多了,持续更新;

[2017.12.23 UPD]

倍增求LCA(以POJ 1986为例 )

Distance Queries

Description

Farmer John’s cows refused to run in his marathon since he chose a path much too long for their leisurely lifestyle. He therefore wants to find a path of a more reasonable length. The input to this problem consists of the same input as in “Navigation Nightmare”,followed by a line containing a single integer K, followed by K “distance queries”. Each distance query is a line of input containing two integers, giving the numbers of two farms between which FJ is interested in computing distance (measured in the length of the roads along the path between the two farms). Please answer FJ’s distance queries as quickly as possible!

Input

* Lines 1..1+M: Same format as “Navigation Nightmare”
* Line 2+M: A single integer, K. 1 <= K <= 10,000
* Lines 3+M..2+M+K: Each line corresponds to a distance query and contains the indices of two farms.

Output

* Lines 1..K: For each distance query, output on a single line an integer giving the appropriate distance.

Sample Input

7 6
1 6 13 E
6 3 9 E
3 5 7 S
4 1 3 N
2 4 20 W
4 7 2 S
3
1 6
1 4
2 6

Sample Output

13
3
36

Hint

Farms 2 and 6 are 20+3+13=36 apart.

Source

USACO 2004 February

代码

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <vector>
#define N 40005
using namespace std;

char bin;
int n,e,a,b,c,T;
int depth[N],dis[N],p[N][20];
bool vis[N];

struct EDGE{
    int to,v;
}edge[N];

vector<EDGE>G[N];
EDGE t;
void addedge(){
    t.to=b;t.v=c;G[a].push_back(t);
    t.to=a;t.v=c;G[b].push_back(t);
}

void dfs(int x){
    vis[x]=1;
    for(int i=1;i<=15;i++){
        if(depth[x]<(1<<i)) break;
        p[x][i]=p[p[x][i-1]][i-1];
    }
    for(int i=0;i<G[x].size();i++){
        if(!vis[G[x][i].to]){
            depth[G[x][i].to]=depth[x]+1;
            dis[G[x][i].to]=dis[x]+G[x][i].v;
            p[G[x][i].to][0]=x;
            dfs(G[x][i].to);
        }
    }
}

int lca(int x,int y){
    if(depth[x]<depth[y]) swap(x,y);
    int t=depth[x]-depth[y];
    for(int i=0;i<=15;i++)
        if(t&(1<<i)) x=p[x][i];
    for(int i=15;i>=0;i--)
        if(p[x][i]!=p[y][i])
            x=p[x][i],y=p[x][i];
    if(x==y) return x;
    return p[x][0];
}

int main(){
    cin>>n>>e;
    for(int i=1;i<=e;i++){
        cin>>a>>b>>c>>bin;
        addedge();
    }
    dfs(1);
    cin>>T;
    while(T--){
        int x,y;
        cin>>x>>y;
        int root=lca(x,y);
        cout<<dis[x]+dis[y]-2*dis[root]<<endl;
    }
    return 0;
}
分享到