Cod sursa(job #634588)

Utilizator marcelcodreaCodrea Marcel marcelcodrea Data 16 noiembrie 2011 18:30:16
Problema Lowest Common Ancestor Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.63 kb
#include<cstdio>
#define N 100005

int p[N];
int mark[N];

int main() {

    int n, m;
    freopen("lca.in","r",stdin);
    freopen("lca.out","w",stdout);

    scanf("%d %d",&n, &m);

    for(int i = 2; i <= n; i++)
     scanf("%d",&p[i]);

    for(int i = 1; i <= m; i++) {
        int x, y, res = 1;
        scanf("%d %d",&x, &y);
        while((x != -1) && (y != -1)) {
            if (mark[x] == i) {res = x; break;}
            mark[x] = i;
            if (mark[y] == i) {res = y; break;}
            mark[y] = i;
            x = p[x];
            y = p[y];
        }
        printf("%d\n", res);
    }
}