Cod sursa(job #634594)

Utilizator marcelcodreaCodrea Marcel marcelcodrea Data 16 noiembrie 2011 18:40:35
Problema Lowest Common Ancestor Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 0.67 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(1) {
            if (mark[x] == i && x != 0) {res = x; break;}
            mark[x] = i;
            if (mark[y] == i && y != 0) {res = y; break;}
            mark[y] = i;
            if(x != 0)
            x = p[x];
            if(y != 0)
            y = p[y];
        }
        printf("%d\n", res);
    }
}