Cod sursa(job #635106)

Utilizator marcelcodreaCodrea Marcel marcelcodrea Data 18 noiembrie 2011 14:22:49
Problema Lowest Common Ancestor Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.31 kb
#include<fstream>
#include<vector>
#define N 100005

using namespace std;

ifstream f("lca.in");
ofstream g("lca.out");

/*struct LNode {
    int v;
    int level;
    LNode* next;
};*/
//int powof2[25];
int n, m;
int M[18][4*N];
int p[N];
int arrH[4*N];
int arrV[4*N];
int aux;
//LNode* r[N];
vector<int> Ladj[N];
int posInEuler[N];
int LG[4*N];
void eulerTour(int ind, int l) {
    arrV[++arrV[0]] = ind;
    arrH[arrV[0]] = l;
    if(Ladj[ind].size() != 0) {
        for(vector<int>::const_iterator it = Ladj[ind].begin(); it != Ladj[ind].end(); it++) {
            eulerTour(*it, l + 1);
            arrV[++arrV[0]] = ind;
            arrH[arrV[0]] = l;
        }
    }
}
/*void insert(LNode*& last, int val) {
    LNode* nou = new LNode();
    nou -> v = val;
    nou -> next = last;
    last = nou;
}*/
void convertToSon() {
    //LNode** r = new LNode*[n + 2];
    /*for(int i = 1; i <= n; i++) {
      r[i] = 0;
    }*/
    for(int i = 2; i <= n; i++) {
        Ladj[p[i]].push_back(i);
    }
}
int min(int a, int b) {
    if(a < b) return a;
    return b;
}
void init(int k) {
    for(int i = 2; i <= k; i++)
     LG[i] = LG[i >> 1] + 1;
}
void RMQ(int p) {
    arrH[0] = arrV[0];
    for(int i = 1; i <= arrH[0]; i++) {
      if(posInEuler[arrV[i]] == 0)
        posInEuler[arrV[i]] = i;
     M[0][i] = i;
    }
    int nr = arrH[0];
    init(nr);
    for(int i = 1; i <= 18; i++)  {
        int wh2go = nr - (1 << i) + 1;
        for(int j = 1; j <= wh2go; j++)
         if (arrH[M[i-1][j]] < arrH[M[i-1][j + (1 << (i - 1))]])
          M[i][j] = M[i-1][j];
         else
          M[i][j] = M[i-1][j + (1 << (i - 1))];
    }

    for(int i = 1; i <= p; i++) {
        int x, y;
        f >> x >> y;
        int lf = posInEuler[x];
        int right = posInEuler[y];
        if(lf > right) {
            lf = posInEuler[y];
            right = posInEuler[x];
        }
        int how = right - lf + 1;
        int p = LG[how];
        if(arrH[M[p][lf]] < arrH[M[p][right - (1 << p) + 1]])
         g << arrV[M[p][lf]] << "\n";
        else
         g << arrV[M[p][right- (1 << p) + 1]] << "\n";
    }

}
int main() {
    f >> n >> m;
    for(int i = 2; i <= n; i++)
     f >> p[i];
    convertToSon();
    eulerTour(1, 0);
    RMQ(m);
    return 0;
}