Cod sursa(job #2358333)

Utilizator Ciprian_PizzaVasile Capota Ciprian_Pizza Data 28 februarie 2019 00:05:38
Problema Lowest Common Ancestor Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 kb
#include <bits/stdc++.h>
#define nmax 100001

using namespace std;

ofstream fout("lca.out");
ifstream fin("lca.in");

int n,m,ancestor;
vector <int> L[nmax];
bitset <nmax> viz;

inline void BFS(int x, int y)
{
    int nod;
    queue <int> q;
    viz.reset();
    q.push(x);
    q.push(y);
    viz[x] = viz[y] = 1;
    while(!q.empty())
    {
        nod = q.front();
        q.pop();
        for(auto i : L[nod])
            if(viz[i] == 0)
            {
                viz[i] = 1;
                q.push(i);
            }
            else
            {
                ancestor = i;
            }
    }
}

int main()
{
    int x,y;
    fin >> n >> m;
    y = 2;
    n--;
    while(n--)
    {
        fin >> x;
        L[y].push_back(x);
        y++;
    }
    while(m--)
    {
        fin >> x >> y;
        if(x == y) ancestor = x;
        else BFS(x,y);
        fout << ancestor << "\n";
    }

    fin.close();
    fout.close();
    return 0;
}