Cod sursa(job #1700782)

Utilizator mihai995mihai995 mihai995 Data 11 mai 2016 09:54:04
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <fstream>
#include <vector>
using namespace std;

const int N = 1 + 1e5;

int head[N], start[N], stop[N], timp, n;
vector<int> sons[N];

void mark(int x, int H){
    head[x] = H;
    for (int y : sons[x])
    	if ( !head[y] )
    		mark(y, H);
}
int dfs(int x){
    start[x] = ++timp;
    int weight = 1, best = -1, son;
    for (int y : sons[x]){
    	int val = dfs(y);
    	weight += val;
    	if ( best < val ){
    		best = val;
    		son = y;
    	}
    }
    for (int y : sons[x])
    	if ( y != son )
    		mark(y, x);
    stop[x] = ++timp;
    return weight;
}
inline int isAncestor(int T, int x){
    return start[T] <= start[x] && stop[x] <= stop[T];
}
int lca(int a, int b){
    int x = a, y = b;
    while (!isAncestor(x, b))
        x = head[x];
    while (!isAncestor(y, a))
        y = head[y];
    return isAncestor(y, x) ? x : y;
}
inline void prepare(int root){
	dfs(root); mark(root, root);
}

int main(){
    ifstream in("lca.in");
    ofstream out("lca.out");
    int nrQ, x, y;

    in >> n >> nrQ;
    for (int i = 2 ; i <= n ; i++){
        in >> x;
        sons[x].push_back(i);
    }
    prepare(1);

    while (nrQ--){
        in >> x >> y;
        out << lca(x, y) << '\n';
    }
    return 0;
}