Cod sursa(job #1127178)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 27 februarie 2014 11:28:31
Problema Lowest Common Ancestor Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.23 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <bitset>
#include <string.h>
#include <algorithm>
#include <iomanip>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <set>
#include <map>
#include <string>
#include <queue>
#include <deque>

using namespace std;

const char infile[] = "lca.in";
const char outfile[] = "lca.out";

ifstream fin(infile);
ofstream fout(outfile);

const int MAXN = 100005;
const int MAXK = 25;
const int oo = 0x3f3f3f3f;

typedef vector<int> Graph[MAXN];
typedef vector<int> :: iterator It;

const inline int min(const int &a, const int &b) { if( a > b ) return b;   return a; }
const inline int max(const int &a, const int &b) { if( a < b ) return b;   return a; }
const inline void Get_min(int &a, const int b)    { if( a > b ) a = b; }
const inline void Get_max(int &a, const int b)    { if( a < b ) a = b; }

/// lca 2 ^ K ancestorsc
/// O ( N log (N) + M log(N))

int N, M;
int ancestor[25][MAXN], level[MAXN];
Graph G;

inline void buildAncestors() {
    for(int k = 1 ; k <= MAXK ; ++ k)
        for(int i = 1 ; i <= N ; ++ i)
            ancestor[k][i] = ancestor[k - 1][ancestor[k - 1][i]];

}

inline void buildLevels(int Node, int Father) {
    level[Node] = level[Father] + 1;
    for(It it = G[Node].begin(), fin = G[Node].end(); it != fin ; ++ it)
        if(*it != Father)
            buildLevels(*it, Node);
}

inline int LCA(int x, int y) {
    if(level[x] < level[y])
        swap(x, y);
    for(int k = MAXK - 1 ; k >= 0 ; -- k)
        if(level[x] - (1 << k) >= level[y])
            x = ancestor[k][x];
    if(x == y)
        return x;
    for(int k = MAXK - 1 ; k >= 0 ; -- k)
        if(ancestor[k][x] != ancestor[k][y]) {
            x = ancestor[k][x];
            y = ancestor[k][y];
        }
    return ancestor[0][x];
}

int main() {
    fin >> N >> M;
    for(int i = 2 ; i <= N ; ++ i) {
        int x;
        fin >> x;
        G[x].push_back(i);
        ancestor[0][i] = x;
    }
    buildAncestors();
    buildLevels(1, 0);
    for(int i = 1 ; i <= M; ++ i) {
        int x, y;
        fin >> x >> y;
        fout << LCA(x, y) << '\n';
    }
    fin.close();
    fout.close();
    return 0;
}