Cod sursa(job #773656)

Utilizator PlayLikeNeverB4George Marcus PlayLikeNeverB4 Data 2 august 2012 12:10:21
Problema Lowest Common Ancestor Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.78 kb
#include <cstdio>
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <sstream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <ctype.h>
#include <cstring>
#include <ctime>

using namespace std;

#define MAXN 100005
vector<int> graph[MAXN];
vector<pair<int, int> > pairs[MAXN];
bool color[MAXN];
int answer[MAXN], ancestor[MAXN];
int L[MAXN], T[MAXN], R[MAXN];
int t, x, y, N, M;

void unite(int x, int y) {
    if(R[x] >= R[y]) {
        T[y] = x;
        if(R[x] == R[y])
            R[x]++;
    }
    else T[x] = y;
}

int find(int x) {
    int root = x;
    while(T[root] != root)
        root = T[root];
    return root;
}

void tarjan(int node) {
    ancestor[node] = node;
    for(size_t i = 0; i < graph[node].size(); i++) {
        int v = graph[node][i];
        tarjan(v);
        unite(node, v);
        ancestor[find(node)] = node;
    }
    color[node] = true;
    for(vector<pair<int, int> > :: iterator it = pairs[node].begin(); it != pairs[node].end(); it++)
        if(color[it->first] == true)
            answer[it->second] = ancestor[find(it->first)];
}

int main() {
	freopen("lca.in", "r", stdin);
	freopen("lca.out","w", stdout);

    scanf("%d %d", &N, &M);

    for(int i = 2; i <= N; i++) {
        scanf("%d", &t);
        graph[t].push_back(i);
    }

    for(int i = 1; i <= N; i++) {
        T[i] = i;
        R[i] = 1;
    }

    for(int i = 0; i < M; i++) {
        scanf("%d %d", &x, &y);

        pairs[x].push_back(make_pair(y, i));
        pairs[y].push_back(make_pair(x, i));
    }

    tarjan(1);

    for(int i = 0; i < M; i++)
        printf("%d\n", answer[i]);

	return 0;
}