Cod sursa(job #1173271)

Utilizator romircea2010FMI Trifan Mircea Mihai romircea2010 Data 19 aprilie 2014 00:02:36
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.67 kb
#include <fstream>
#include <vector>
#define ch buffer[position]
#define Next ++ position == limit ? f.read(buffer, limit), position = 0 : 0

using namespace std;

const int NMax = 100010, TMax = 2000000, limit = 1024 * 1024;

ifstream f ("lca.in");
int position;
char buffer[limit];
int N, T;
int K;
int first[NMax], last[NMax];
vector <int> G[NMax];
int ancestor[17][NMax];

inline void Read(int &x)
{
    for (; ch < '0' || ch > '9'; Next);
    for (x = 0; '0' <= ch && ch <= '9'; x = x * 10 + ch - '0', Next);
}

inline void Read(int &x, int &y)
{
    Read(x), Read(y);
}


inline void DFS(const int &node, const int &father)
{
    first[node] = ++ K;
    ancestor[0][node] = father;
    for (vector <int> :: iterator it = G[node].begin(); it != G[node].end(); ++ it)
        DFS(*it, node);
    last[node] = ++ K;
}

inline int GetLca(int x, const int y)
{
    if (first[x] <= first[y] && last[y] <= last[x])
        return x;
    for (int i = 16; i >= 0; -- i)
        if (ancestor[i][x] && ! (first[ancestor[i][x]] <= first[y] && last[y] <= last[ancestor[i][x]]))
            x = ancestor[i][x];
    return ancestor[0][x];
}

int main()
{
    f.read(buffer, limit);
    Read(N), Read(T);
    for (int i = 2; i <= N; ++ i)
    {
        int father; Read(father);
        G[father].push_back(i);
    }

    DFS(1, 0);

    for (int i = 1; (1 << i) <= N; ++ i)
        for (int j = 1; j <= N; ++ j)
            ancestor[i][j] = ancestor[i-1][ancestor[i-1][j]];
    ofstream g("lca.out");
    for (int t = 1; t <= T; ++ t)
    {
        int x, y; Read(x), Read(y);
        g << GetLca(x, y) << "\n";
    }
    g.close();
    return 0;
}