Cod sursa(job #1548511)

Utilizator tudormaximTudor Maxim tudormaxim Data 10 decembrie 2015 23:38:32
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.13 kb
#include <iostream>
#include <fstream>
#include <cmath>
#include <vector>
using namespace std;
const int nmax = 1e5+5;
vector <int> g[nmax];
int p[nmax], h[nmax], t[nmax];

int lca(int x, int y)
{
    while(p[x]!=p[y])
    {
        if(h[x] > h[y]) x=p[x];
        else y=p[y];
    }
    while(x!=y)
    {
        if(h[x] > h[y]) x=t[x];
        else y=t[y];
    }
    return x;
}

void dfs(int dad, int x)
{
    if(h[dad] < x) p[dad] = 1;
    else if(h[dad]%x==0) p[dad]=t[dad];
    else p[dad]=p[t[dad]];
    int i, son;
    for(i=0; i<g[dad].size(); i++)
    {
        son=g[dad][i];
        dfs(son, x);
    }
}

int main()
{
    ifstream fin("lca.in");
    ofstream fout("lca.out");
    ios_base::sync_with_stdio(false);
    int n, m, x, y, hmax = 0, i;
    fin >> n >> m;
    for(i=2; i<=n; i++)
    {
        fin >> t[i];
        g[t[i]].push_back(i);
        h[i] = h[t[i]] + 1;
        hmax=max(hmax, h[i]);
    }

    dfs(1, sqrt(hmax));
    for(i=1; i<=m; i++)
    {
        fin >> x >> y;
        fout << lca(x, y) << "\n";
    }
    fin.close();
    fout.close();
    return 0;
}