Cod sursa(job #2046481)

Utilizator flaviu_2001Craciun Ioan-Flaviu flaviu_2001 Data 23 octombrie 2017 20:34:47
Problema Lowest Common Ancestor Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.65 kb
#include <bits/stdc++.h>

using namespace std;

struct thing{
    int x, d;
};

int n, test, p, depth[100005], tt[100005], euclid[200005], first_pos[100005], lg2[100005];
thing pd[20][100005];
vector<int> v[100005];

thing min(thing a, thing b)
{
    if(a.d < b.d)
        return a;
    return b;
}

thing make_thing(int x, int d)
{
    thing aux;
    aux.x = x;
    aux.d = d;
    return aux;
}

void dfs (int x)
{
    depth[x] = depth[tt[x]]+1;
    ++p;
    euclid[p] = x;
    first_pos[x] = p;
    for (vector<int>::iterator it = v[x].begin(); it != v[x].end(); ++it){
        dfs(*it);
        euclid[++p] = x;
    }
}

void build_rmq()
{
    for (int i = 1; i < p; ++i){
        pd[0][i] = make_thing(euclid[i], depth[euclid[i]]);
        if(depth[euclid[i]] > depth[euclid[i+1]])
            pd[0][i] = make_thing(euclid[i+1], depth[euclid[i+1]]);
    }
    for (int t = 1; t <= lg2[p-1]; ++t)
        for (int i = 1; i <= p-(1<<t); ++i)
            pd[t][i] = min(pd[t-1][i], pd[t-1][i+(1<<(t-1))]);
}

int query(int x, int y)
{
    if (x == y)
        return x;
    int sz = lg2[first_pos[y]-first_pos[x]];
    thing aux = min(pd[sz][first_pos[x]], pd[sz][first_pos[y]-(1<<sz)]);
    return aux.x;
}

int main()
{
    ifstream fin ("lca.in");
    ofstream fout ("lca.out");
    fin >> n >> test;
    for (int i = 2; i <= n; ++i){
        int x;
        fin >> x;
        v[x].push_back(i);
        tt[i] = x;
    }
    dfs(1);
    lg2[2] = 1;
    for (int i = 3; i <= 100000; ++i)
        lg2[i] = lg2[i/2]+1;
    build_rmq();
    while(test--){
        int x, y;
        fin >> x >> y;
        fout << query(x, y) << "\n";
    }
    fin.close();
    fout.close();
    return 0;
}