Cod sursa(job #1813712)

Utilizator crazylamaRiclea Andrei crazylama Data 23 noiembrie 2016 11:10:13
Problema Lowest Common Ancestor Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.84 kb
#include <fstream>
#include <vector>
#include <queue>
#include <list>
#include <cmath>
using namespace std;

ifstream f("lca.in");
ofstream g("lca.out");

vector<int> Father, Level, Ancestor;
list<int> Leaf;

void DF(int n, int CurrentNode)
{
    bool ok = false;
    for (int i = 2; i <= n; ++i)
        if (Father[i] == CurrentNode)
        {
            Level[i] = Level[CurrentNode] + 1;
            DF(n, i);
            ok = true;
        }
    if (!ok)
        Leaf.push_back(CurrentNode);
}

int main()
{
    int n, m, interval;
    bool ok;
    f >> n >> m;
    Father.resize(n + 1);
    Level.resize(n + 1);
    Ancestor.resize(n + 1);
    Father[1] = Ancestor[1] = Level[1] = 0;
    interval = sqrt(n);
    for (int i = 1; i < n; ++i)
        f >> Father[i + 1];
    DF(n, 1);
    for (list<int>::iterator i = Leaf.begin(); i != Leaf.end(); ++i)
        {
            int ancestor = *i, father = Father[*i];
            for (int j = 0; j < interval; ++j)
                ancestor = Father[ancestor];
            Ancestor[*i] = ancestor;
            while (1)
            {
                Ancestor[father] = Father[Ancestor[*i]];
                if (Father[father])
                    break;
                *i = father;
                father = Father[*i];
            }
        }
    Leaf.clear();
    for (int i = 0; i < m; ++i)
    {
        int x, y;
        f >> x >> y;
        while (Level[Ancestor[x]] > Level[y])
            x = Ancestor[x];
        while (Level[Ancestor[y]] > Level[x])
            y = Ancestor[y];
        while (Level[x] > Level[y])
            x = Father[x];
        while (Level[y] > Level[x])
            y = Father[y];
        while (x != y)
        {
            x = Father[x];
            y = Father[y];
        }
        g << x << "\n";
    }
    return 0;
}