【题目链接】
【算法】
树上倍增,时间复杂度 : O(qklog(n))
【代码】
#include<bits/stdc++.h> using namespace std; #define MAXN 3000010 #define MAXLOG 18 const int INF = 1e8; int T,tot = 1,i,x; char opt[100]; int q[MAXN],dep[MAXN],anc[MAXN][MAXLOG]; inline void update(int x) { int i; tot++; dep[tot] = dep[x] + 1; anc[tot][0] = x; for (i = 1; i < MAXLOG; i++) anc[tot][i] = anc[anc[tot][i-1]][i-1]; } inline int query(int k) { int i,j,t,mn = INF; bool flag = true; for (i = 1; i <= k; i++) mn = min(mn,dep[q[i]]); for (i = 1; i <= k; i++) { t = dep[q[i]] - mn; for (j = 0; j < MAXLOG; j++) { if (t & (1 << j)) q[i] = anc[q[i]][j]; } } for (i = 1; i <= k; i++) flag &= (q[i] == q[1]); if (flag) return q[1]; for (i = MAXLOG - 1; i >= 0; i--) { flag = true; for (j = 1; j <= k; j++) flag &= (anc[q[j]][i] == anc[q[1]][i]); if (!flag) { for (j = 1; j <= k; j++) q[j] = anc[q[j]][i]; } } return anc[q[1]][0]; } int main() { scanf("%d",&T); while (T--) { scanf("%s%d",&opt,&x); if (opt[0] == 'A') update(x); else { for (i = 1; i <= x; i++) scanf("%d",&q[i]); printf("%d ",query(x)); } } return 0; }