Cod sursa(job #1983950)

Utilizator Dragne.Andrei11Dragne Andrei Dragne.Andrei11 Data 22 mai 2017 22:47:27
Problema Lowest Common Ancestor Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 0.84 kb
#include <bits/stdc++.h>

using namespace std;

vector <int> t;
vector <int> depth;

int lca(int u, int v)
{
    while(depth[u]!=depth[v])
    {
        if(depth[u]>depth[v])
            u=t[u];
        else
            v=t[v];
    }
    while(u!=v)
    {
        u=t[u];
        if(u==v)
            return u;
        v=t[v];
    }
    return u;
}

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

    cin>>n>>m;
    t.push_back(0);
    t.push_back(0);
    depth.push_back(0);
    depth.push_back(0);
    for(int i=2;i<=n;i++)
    {
        int nr;
        cin>>nr;
        t.push_back(nr);
        depth.push_back(depth[nr]+1);
    }
    for(int i=1;i<=m;i++)
    {
        int u, v;
        cin>>u>>v;
        cout<<lca(u, v)<<'\n';
    }

    return 0;
}