Cod sursa(job #638962)

Utilizator andrei-alphaAndrei-Bogdan Antonescu andrei-alpha Data 22 noiembrie 2011 02:19:32
Problema Lowest Common Ancestor Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.62 kb
using namespace std;

#include <set>
#include <map>
#include <list>
#include <deque>
#include <stack>
#include <queue>
#include <cmath>
#include <ctime>
#include <cctype>
#include <cstdio>
#include <vector>
#include <string>
#include <bitset>
#include <utility>
#include <iomanip>
#include <fstream>
#include <cstring>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <functional>

#define oo (1<<30)
#define f first
#define s second
#define II inline
#define db double
#define ll long long
#define pb push_back
#define mp make_pair
#define Size(V) ((ll)(V.size()))
#define all(V) (V).begin() , (V).end()
#define CC(V) memset((V),0,sizeof((V)))
#define CP(A,B) memcpy((A),(B),sizeof((B)))
#define FOR(i,a,b) for(int (i)=(a);(i)<=(b);++(i))
#define REP(i, N) for (int (i)=0;(i)<(int)(N);++(i))
#define FORit(it, x) for (__typeof((x).begin()) it = (x).begin(); it != (x).end(); ++it)
#define printll(x) printf("%lld",(x))
#define printsp() printf(" ")
#define newline() printf("\n")
#define readll(x) scanf("%lld",&(x))
#define debugll(x) fprintf(stderr,"%lld\n",(x))

#define N_MAX (1<<17)

typedef vector<int> VI;
typedef pair<int,int> pi;
typedef pair<short int,short int> ps;
typedef vector<string> VS;
template<class T> string toString(T n) {ostringstream ost;ost<<n;ost.flush();return ost.str();}

int N,M;
int Poz[N_MAX],Q[1<<18],H[N_MAX],T[N_MAX];
int Pow2[1<<18],Rmq[18][1<<18]; //twice the size
vector<VI> A(N_MAX);
bool viz[N_MAX];

II void scan()
{
    freopen("lca.in","r",stdin);
    freopen("lca.out","w",stdout);

    scanf("%d%d",&N,&M);
    FOR(i,2,N)
    {
        scanf("%d",T+i);
        A[ T[i] ].pb(i);
    }
}

II void DF(int nod)
{
    viz[nod] = true;
    Q[++Q[0]] = nod;
    Poz[nod] = Q[0];

    FORit(it,A[nod])
        if(!viz[*it])
        {
            H[*it] = H[nod] + 1;
            DF(*it);
            Q[++Q[0]] = nod;
        }

}

II int query_rmq(int x,int y)
{
    if(x > y) swap(x,y);

    int step = Pow2[y - x];
    if(H[ Rmq[step][x] ] < H[ Rmq[step][y - (1<<step) + 1 ] ])
        return Rmq[step][x];
    return Rmq[step][y - (1<<step) + 1];
}

II void solve()
{
    DF(1);

    Pow2[0] = 0;
    Pow2[1] = 0;
    FOR(i,2,Q[0])
        Pow2[i] = Pow2[i / 2] + 1;

    FOR(i,1,Q[0])
        Rmq[0][i] = Q[i];

    FOR(step,1,17)
    FOR(i,1,Q[0])
    {
        int j = i + (1<<step - 1);

        Rmq[step][i] = Rmq[step - 1][i];
        if(H[ Rmq[step - 1][i] ] > H[ Rmq[step - 1][j]  ])
            Rmq[step][i] = Rmq[step - 1][j];
    }

    int x,y;
    FOR(i,1,M)
    {
        scanf("%d%d",&x,&y);
        printf("%d\n", query_rmq(Poz[x],Poz[y]) );
    }
}

int main()
{
    scan();
    solve();
    return 0;
}