Cod sursa(job #1537209)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 27 noiembrie 2015 00:41:46
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 100000 + 1;

vector<int> G[MAX_N];
int depth[MAX_N], father[MAX_N], size[MAX_N], path[MAX_N];
int posInPath[MAX_N], lengthPath[MAX_N], startNode[MAX_N];
int N, Q;
int numberOfPaths;

void dfs(int node)
{
    int heavySon = 0;

    size[node] = 1;

    for (int v : G[node])
    {
        if (father[v] == 0)
        {
            father[v] = node;
            depth[v] = depth[node] + 1;

            dfs(v);

            size[node] += size[v];

            if (size[heavySon] < size[v])
                heavySon = v;
        }
    }

    if (heavySon == 0)
        path[node] = numberOfPaths++;
    else
        path[node] = path[heavySon];

    posInPath[node] = lengthPath[ path[node] ]++;
}

void build_heavy()
{
    father[1] = 1;
    depth[1] = 1;
    dfs(1);

    for (int i = 1; i <= N; ++i)
    {
        posInPath[i] = lengthPath[ path[i] ] - posInPath[i] - 1;

        if (posInPath[i] == 0)
            startNode[ path[i] ] = i;
    }
}

int lca(int x, int y)
{
    while (path[x] != path[y])
    {
        if (depth[ startNode[ path[x] ] ] < depth[ startNode[ path[y] ] ])
            y = father[ startNode[ path[y] ] ];
        else
            x = father[ startNode[ path[x] ] ];
    }

    return posInPath[x] < posInPath[y] ? x : y;
}

int main()
{
    ifstream in("lca.in");
    ofstream out("lca.out");

    in >> N >> Q;

    for (int i = 2; i <= N; ++i)
    {
        int t;
        in >> t;

        G[t].push_back(i);
    }

    build_heavy();

    while (Q--)
    {
        int x, y;
        in >> x >> y;

        out << lca(x, y) << "\n";
    }

    return 0;
}