Cod sursa(job #2150966)

Utilizator andrei.gramescuAndrei Gramescu andrei.gramescu Data 3 martie 2018 22:17:17
Problema Lowest Common Ancestor Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 0.91 kb
#include <cstdio>
#include <vector>
using namespace std;
#define NMAX 100005

int n, m;
vector<int> ad[NMAX];

int lca(int root, int a, int b){
    int q1, q2, h = 0;
    if(root == a || root == b)
        return root;
    int i;
    int rez = 0;
    for(i=0; i<(int) ad[root].size(); i++){
        rez = lca(ad[root][i], a, b);
        if(rez)
            q1 = rez, h++;
        if(h == 2)
            return root;
    }

    if(h)
        return q1;

    return 0;
}

int main(){

    int i, x, y;
    FILE *fin, *fout;
    fin = fopen("lca.in", "r");
    fout = fopen("lca.out", "w");

    fscanf(fin, "%d %d", &n, &m);
    for(i=1; i<=n-1; i++){
        fscanf(fin, "%d", &x);
        ad[x].push_back(i + 1);
    }

    for(i=1; i<=m; i++){
        fscanf(fin, "%d %d", &x, &y);
        fprintf(fout, "%d\n", lca(1, x, y));
    }

    fclose(fin);
    fclose(fout);
    return 0;
}