Cod sursa(job #1614562)

Utilizator CiurezAndreiCiurez Marius-Andrei CiurezAndrei Data 25 februarie 2016 23:44:41
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.66 kb
#include <fstream>
#include <vector>

#define DIM 100010
using namespace std;

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

int LEVEL[3 * DIM], E[3 * DIM], A[23][3 * DIM], N, M, P[3 * DIM], k, x, v[3*DIM];
vector<int>L[DIM];

void dfs(int node, int lev)
{
    E[++k] = node;
    v[node] = k;
    LEVEL[k] = lev;

    for(int i = 0; i < L[node].size(); i ++)
    {
        dfs(L[node][i], lev + 1);

        E[++k] = node;
        LEVEL[k] = lev;
    }
}

void process()
{
    for(int i = 1; (1 << i) <= k; i ++)
    {
        for(int j = 1; j + (1 << (i - 1)) <= k; j ++)
        {
            if(LEVEL[A[i - 1][j]] > LEVEL[A[i - 1][j + (1 << (i - 1))]])
            {
                A[i][j] = A[i - 1][j + (1 << (i - 1))];
            }
            else
            {
                A[i][j] = A[i - 1][j];
            }
        }
    }
}

int RMQ(int a, int b)
{
    if(LEVEL[ A[ P[b - a + 1] ][a] ] > LEVEL[ A[ P[b - a + 1] ][b - (1 << P[b - a + 1]) + 1]])
    {
        return E[ A[ P[b - a + 1] ][b - (1 << P[b - a + 1]) + 1] ];
    }
    else
    {
        return E[ A[ P[b - a + 1] ][a] ];
    }
}

int main()
{
    fin >> N >> M;

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

    dfs(1, 0);

    for(int i = 2; i <= k; i ++)
    {
        P[i] = 1 + P[i / 2];
    }

    for(int i = 1; i <= k; i ++)
    {
        A[0][i] = i;
    }

    process();

    for(int i = 1; i <= M; i ++)
    {
        int a, b;
        fin >> a >> b;
        if(v[a] > v[b])
            swap(a, b);
        fout << RMQ(v[a], v[b]) << '\n';
    }


    return 0;
}