Cod sursa(job #1812397)

Utilizator crazylamaRiclea Andrei crazylama Data 22 noiembrie 2016 00:58:38
Problema Lowest Common Ancestor Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 2.16 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, LeafVector;

int main()
{
    int n, m, interval;
    f >> n >> m;
    Father.resize(n + 1);
    Level.resize(n + 1);
    Ancestor.resize(n + 1);
    LeafVector.resize(n + 1);
    Father[1] = Ancestor[1] = Level[1] = 0;
    LeafVector[1] = 1;
    interval = sqrt(n);
    for (int i = 1; i < n; ++i)
    {
        f >> Father[i + 1];
        LeafVector[Father[i + 1]] = 1;
    }
    int nodCurrent = 1;
    queue<int> Queue;
    list<int> Leaf;
    Queue.push(nodCurrent);
    while (!Queue.empty())
    {
        for (int i = 2; i <= n; ++i)
            if (Father[i] == nodCurrent)
            {
                Queue.push(i);
                Level[i] = Level[nodCurrent] + 1;
            }
        Queue.pop();
        nodCurrent = Queue.front();
    }
    for (int i = 2; i <= n; ++i)
        if (!LeafVector[i])
            Leaf.push_back(i);
    LeafVector.resize(0);
    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[x] > Level[y] && Level[Ancestor[x]] > Level[y])
            x = Ancestor[x];
        while (Level[y] > Level[x] && 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;
}