Pagini recente » Cod sursa (job #1949006) | Cod sursa (job #1191242) | Cod sursa (job #355406) | Cod sursa (job #54730) | Cod sursa (job #1537108)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
const int NMax = 1e5 + 5;
int Chains;
int Level[NMax], Height[NMax], Chain[NMax], Parent[NMax];
vector < int > G[NMax];
void DFS(int node){
Height[node] = 1;
int Optimal = 0;
for(auto son: G[node]){
Level[son] = Level[node] + 1;
DFS(son);
Height[node] += Height[son];
Parent[Chain[son]] = node;
if(Height[son] > Height[Optimal]) Optimal = son;
}
if(!Optimal){
Chain[node] = ++Chains;
} else {
Chain[node] = Chain[Optimal];
}
}
inline int LCA(int &x, int &y){
while(Chain[x] != Chain[y]){
if(Level[Parent[Chain[x]]] >= Level[Parent[Chain[y]]]){
x = Parent[Chain[x]];
} else {
y = Parent[Chain[y]];
}
}
return Level[x] <= Level[y] ? x : y;
}
int main(){
int n, k, x, y;
fin >> n >> k;
for(int i = 2; i <= n; i++){
fin >> x;
G[x].push_back(i);
}
Level[1] = 1;
DFS(1);
Parent[Chain[1]] = 0;
while(k--){
fin >> x >> y;
fout << LCA(x, y) << "\n";
}
for(int i = 1; i <= n; i++) fout << Chain[i] << " ";
return 0;
}