Cod sursa(job #2718189)

Utilizator codruta.miron08Miron Ioana Codruta codruta.miron08 Data 8 martie 2021 16:01:30
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("lca.in");
vector <int > tree[100005];
vector <int > euler[400005];
vector <int > ind[400005];
int n,q,k;
bool viz[100005];
void dfs(int st,int index)
{
    viz[st] = true;
    ind[k].push_back(index);
    euler[k++].push_back(st);
        for (auto &v : tree[st]) {
            if (!viz[v]) {
                dfs(v, index + 1);
                euler[k].push_back(st);
                 ind[k++].push_back(index);
            }
}
}
void citire()
{
    int x,y,q;
    fin >> n >> q;
    for(int i = 2; i <= n ; i++)
    {
        fin >> x;
        tree[i].push_back(x);
         tree[x].push_back(i);
    }
    dfs(1,1);
   for(int i = 0; i < q; i++)
   {
       int node,ok = 0,mini = 999;
        fin >> x >> y;
        for(int j = 0; j < k; j++)
        {

            if(euler[j][0]== x && ok == 0)
                ok = 1;

                if(ok == 1)
                {
                    if(ind[j][0] < mini)
                        mini = ind[j][0], node = euler[j][0];
                }
                if(ok == 1 && euler[j][0]== y)
                break;

        }
        fout << node << "\n";
}
   }

int main()
{
   citire();
    return 0;
}