Cod sursa(job #1133157)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 4 martie 2014 15:52:02
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.36 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 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 with Heavy Path Decomposition
    N log N / query
**/

int N, M, numPaths;
int pathWhere[MAXN], pathFather[MAXN], depth[MAXN], heavy[MAXN];
Graph G;

void DFs(int Node, int Father, int actLevel) {
    heavy[Node] = 1;
    depth[Node] = actLevel;
    int heaviest = -1;
    for(It it = G[Node].begin(), fin = G[Node].end(); it != fin ; ++ it) {
        if(*it == Father)
            continue;
        DFs(*it, Node, actLevel + 1);
        heavy[Node] += heavy[*it];
        if(heaviest == -1)
            heaviest = *it;
        else if(heavy[heaviest] < heavy[*it])
            heaviest = *it;
    }
    if(heaviest == -1) {
        pathWhere[Node] = ++ numPaths;
        pathFather[pathWhere[Node]] = Father;
        return;
    }
    pathWhere[Node] = pathWhere[heaviest];
    pathFather[pathWhere[Node]] = Father;
}

int LCA(int x, int y) {
    if(pathWhere[x] == pathWhere[y]) {
        if(depth[x] > depth[y])
            swap(x, y);
        return x;
    }
    if(depth[pathFather[pathWhere[x]]] < depth[pathFather[pathWhere[y]]])
        swap(x, y);
    return LCA(pathFather[pathWhere[x]], y);
}

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