Pagini recente » Cod sursa (job #2878006) | Cod sursa (job #708526) | Cod sursa (job #388236) | Cod sursa (job #36250) | Cod sursa (job #3297561)
#include <fstream>
#include <queue>
#include <vector>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <map>
#include <unordered_map>
#include <string>
#include <unordered_set>
#include <set>
using namespace std;
ifstream cin("lca.in");
ofstream cout("lca.out");
const int NMAX = 100005;
//const long long INF = 1e18;
const int INF=(1<<30);
const int MOD=1000000007;
const int ALPHABET_SIZE=26;
const int MAX_LEVELS=20;
using ull = unsigned long long;
using sll = signed long long;
using ll = long long;
using ui = unsigned int;
using pii = pair<int, int>;
int n,x,idx,t,k,m;
vector<int> graph[NMAX];
int depth[NMAX],parents[NMAX][MAX_LEVELS];
void DFS(int node,int parent) {
parents[node][0]=parent;
for (auto i:graph[node]) {
if (i!=parent) {
depth[i]=depth[node]+1;
DFS(i,node);
}
}
}
int LCA(int x,int y) {
if (depth[x]<depth[y]) swap(x,y);
for (int i=MAX_LEVELS-1;i>=0;i--) {
if (depth[x]>=depth[y]+(1<<i)) x=parents[x][i];
}
if (x==y) return x;
for (int i=MAX_LEVELS-1;i>=0;i--) {
if (parents[x][i] && parents[x][i]!=parents[y][i]) {
x=parents[x][i];
y=parents[y][i];
}
}
return parents[x][0];
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin>>n>>m;
for (int i = 2; i <= n; i++) {
int parent;
cin >> parent;
graph[parent].push_back(i);
graph[i].push_back(parent);
}
DFS(1, 0);
while (m--) {
int x, y;
cin >> x >> y;
cout << LCA(x, y) << '\n';
}
return 0;
}