Cod sursa(job #2492356)

Utilizator IATI2019Iati Shumen IATI2019 Data 14 noiembrie 2019 17:08:56
Problema Lowest Common Ancestor Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.73 kb
#include <bits/stdc++.h>

using namespace std;
class InParser {
private:
	FILE *fin;
	char *buff;
	int sp;

	char read_ch() {
		++sp;
		if (sp == 4096) {
			sp = 0;
			fread(buff, 1, 4096, fin);
		}
		return buff[sp];
	}

public:
	InParser(const char* nume) {
		fin = fopen(nume, "r");
		buff = new char[4096]();
		sp = 4095;
	}

	InParser& operator >> (int &n) {
		char c;
		while (!isdigit(c = read_ch()) && c != '-');
		int sgn = 1;
		if (c == '-') {
			n = 0;
			sgn = -1;
		} else {
			n = c - '0';
		}
		while (isdigit(c = read_ch())) {
			n = 10 * n + c - '0';
		}
		n *= sgn;
		return *this;
	}

	InParser& operator >> (long long &n) {
		char c;
		n = 0;
		while (!isdigit(c = read_ch()) && c != '-');
		long long sgn = 1;
		if (c == '-') {
			n = 0;
			sgn = -1;
		} else {
			n = c - '0';
		}
		while (isdigit(c = read_ch())) {
			n = 10 * n + c - '0';
		}
		n *= sgn;
		return *this;
	}
};
vector <int> tour;
vector <int> v[200001];
bitset <200001> viz;
int lvl[200001];
int n;
int rmq[18][200001],logs[200001];
map <int,int> mp;
void DFS(int nod,int level){
    lvl[nod] = level;
    tour.push_back(nod);
    mp[nod] = tour.size() - 1;
    viz[nod] = 1;
    for(auto x : v[nod]){
        if(!viz[x]){
            DFS(x,level + 1);
            tour.push_back(nod);
            mp[nod] = tour.size() - 1;
        }
    }
}
void compute(){
    int i,j,lung;
    for(i = 1;i < tour.size();i++){
        rmq[0][i] = tour[i];
    }
    for(i = 2;i <= tour.size() - 1;i++){
        logs[i] = logs[i/2] + 1;
    }
    for(i = 1;i <= logs[tour.size() - 1];i++){
        int lung = 1 << i;
        for(j = 1;j + lung - 1 <= tour.size() - 1;j++){
            int a = rmq[i-1][j];
            int b = rmq[i-1][j + lung/2];
            if(lvl[a] > lvl[b])
                rmq[i][j] = b;
            else
                rmq[i][j] = a;
        }
    }
}
int getmin(int a,int b){
    a = mp[a];
    b = mp[b];
    if(b < a)
        swap(a,b);
    int cv = logs[b - a + 1];
    int lung = 1 << cv;
    int x = rmq[cv][a];
    int y = rmq[cv][b - lung + 1];
    if(lvl[x] > lvl[y])
        return y;
    return x;
}
int main()
{
    InParser cin("lca.in");
    ofstream cout("lca.out");
    int m,i,x;
    cin >> n >> m;
    tour.push_back(0);
    for(i = 2;i <= n;i++){
        cin >> x;
        if(x != i){
            v[x].push_back(i);
            v[i].push_back(x);
        }
    }
    for(i = 1;i <= n;i++){
        if(!viz[i]){
            DFS(i,1);
        }
    }    compute();

    //for(auto x : tour)
       // cout << x << " ";
    while(m--){
        int y;
        cin >> x >> y;
        cout << getmin(x,y) << "\n";
    }
    return 0;
}