Cod sursa(job #2307701)

Utilizator andreicoman299Coman Andrei andreicoman299 Data 25 decembrie 2018 14:35:04
Problema Lowest Common Ancestor Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <bits/stdc++.h>
#define MAXN 100000
#define MAXQ 2000000

int n;
std::vector <int> G[1 + MAXN];
struct Query{int index, node;};
std::vector <Query> Q[1 + MAXN];

int father[1 + MAXN];
inline void Union(int x, int y){
    father[y] = x;
}
inline int Find(int x){
    if(father[x] == 0)
        return x;
    return father[x] = Find(father[x]);
}

bool color[1 + MAXN];
int ans[1 + MAXQ];
void dfs(int node, int papa){
    for(auto y: G[node]) if(y != papa){
        dfs(y, node);
        Union(node, y);
    }
    color[node] = 1;
    for(auto y: Q[node]) if(color[y.node])
        ans[y.index] = Find(y.node);
}

int main(){
    FILE*fi,*fo;
    fi = fopen("lca.in","r");
    fo = fopen("lca.out","w");

    int m;
    fscanf(fi,"%d%d", &n, &m);
    for(int i = 2; i <= n; i++){
        int x;
        fscanf(fi,"%d", &x);
        G[i].push_back(x);
        G[x].push_back(i);
    }

    for(int i = 1; i <= m; i++){
        int x, y;
        fscanf(fi,"%d%d", &x, &y);
        Q[x].push_back({i, y});
        Q[y].push_back({i, x});
    }
    dfs(1, 0);

    for(int i = 1; i <= m; i++)
        fprintf(fo,"%d\n", ans[i]);

    return 0;
}