Pagini recente » Cod sursa (job #2509829) | Cod sursa (job #1085817) | Cod sursa (job #2388841) | Cod sursa (job #1089572) | Cod sursa (job #3142934)
#include <fstream>
#include <vector>
using namespace std;
ifstream cin("lca.in");
ofstream cout("lca.out");
struct nod{
int father;
int depth;
nod(){
father = 0;
depth = 0;
}
nod(int father, int depth) {
this->father = father;
this->depth = depth;
}
};
const int N = 1e5;
vector <nod> noduri;
///first father, second depth
const int putere = 17;
int tata[putere + 1][N + 5];
void same_depth(int &st, int &dr){
if(noduri[st].depth > noduri[dr].depth)
swap(st, dr);
for(int i = putere; i >= 0; i--){
int adanc = 1 << i;
if(noduri[dr].depth - adanc >= 1 and noduri[dr].depth - adanc <= noduri[st].depth)
dr = tata[i][dr];
}
}
int lca(int st, int dr){
if(st == dr)
return st;
if (noduri[st].depth != noduri[dr].depth)
same_depth(st, dr);
for (int p = putere; p >= 0; p--)
if (tata[p][st] != 0 && tata[p][dr] != 0 && tata[p][st] != tata[p][dr])
{
st = tata[p][st];
dr = tata[p][dr];
}
return tata[0][st];
}
int main() {
noduri.resize(1);
noduri.push_back(nod(0, 1));
int n, m;
cin >> n >> m;
///citire
for(int i = 2; i <= n; i++) {
int x;
cin >> x;
noduri.push_back({x, noduri[x].depth + 1});
}
///initializare
for(int i = 1; i <= n; i++){
tata[0][i] = noduri[i].father;
}
for (int i = 1; i < putere; i++)
for (int j = 1; j <= n; j++)
tata[i][j] = tata[i - 1][tata[i - 1][j]];
///afisare
for(int i = 0; i < m; i++){
int x1, x2;
cin >> x1 >> x2;
cout << lca(x1, x2) << '\n';
}
return 0;
}