Cod sursa(job #2415321)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 25 aprilie 2019 19:38:00
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#include <fstream>
#include <vector>

using namespace std;

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

const int NMAX = 100000;
const int LOGMAX = 18;

int N, M;
vector <int> sons[NMAX + 5];

int height[NMAX + 5], firstAp[NMAX + 5];

vector <int> rmq[LOGMAX + 5];

void DFS(int node, int dad)
{
    height[node] = 1 + height[dad];

    firstAp[node] = rmq[0].size();

    rmq[0].push_back(node);

    for(auto it : sons[node])
    {
        DFS(it, node);
        rmq[0].push_back(node);
    }
}

int GetLowerHeight(int x, int y)
{
    if(height[x] < height[y])
        return x;

    return y;
}

void BuildRmq()
{
    for(int i = 1; i <= LOGMAX; i++)
    {
        if((1 << i) > rmq[0].size())
            break;

        for(int j = 0; j <= rmq[0].size(); j++)
            if(j + (1 << i) > rmq[0].size())
                break;
            else
                rmq[i].push_back(GetLowerHeight(rmq[i - 1][j], rmq[i - 1][j + (1 << (i - 1))]));
    }
}

int QueryRmq(int x, int y)
{
    x = firstAp[x];
    y = firstAp[y];

    if(x > y)
        swap(x, y);

    int l = y - x + 1;
    int k = 0;

    while((1 << k) <= l)
        k++;
    k--;

    return GetLowerHeight(rmq[k][x], rmq[k][y - (1 << k) + 1]);
}

int main()
{
    int x, y;

    fin >> N >> M;

    for(int i = 2; i <= N; i++)
    {
        fin >> x;
        sons[x].push_back(i);
    }

    DFS(1, 0);

    BuildRmq();

    for(int i = 1; i <= M; i++)
    {
        fin >> x >> y;
        fout << QueryRmq(x, y) << '\n';
    }

    return 0;
}