社区讨论

求调必关

P10113[GESP202312 八级] 大量的工作沟通参与者 2已保存回复 2

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
2 条
当前快照
1 份
快照标识符
@mhj237s1
此快照首次捕获于
2025/11/03 19:27
4 个月前
此快照最后确认于
2025/11/03 19:27
4 个月前
查看原帖
CPP
#include <bits/stdc++.h>
using namespace std;


const int MAXLOG=22;
const int MAXN=100005;
int m,LCA;
int n;
vector<int> g[MAXN];
int q,p;
int anc[MAXN][MAXLOG+2];
int depth[MAXN];

int dfs(int x){
	depth[x]=depth[anc[x][0]]+1;
	for(int i=1;i<MAXLOG;i++){
		anc[x][i]=anc[anc[x][i-1]][i-1];
	}
	for(int i=0;i<g[x].size();i++){
		if(g[x][i]!=anc[x][0])dfs(g[x][i]);
	}
	return 0;
}
int getLCA(int u,int v){
	if(depth[u]<depth[v]){
		swap(u,v);
	} //使u更深
	int mLOG=21;
	while(depth[u]>depth[v]){
		if(depth[anc[u][mLOG]]>=depth[v]){
//			cout<<"u="<<u<<" v="<<v<<endl;
			u=anc[u][mLOG];
		}
		mLOG--;
	} 
//	cout<<"u="<<u<<" v="<<v<<endl;
	if(u==v){
		return u;
	}
	mLOG=21;
	while(anc[u][mLOG]!=anc[v][mLOG]){
		if(anc[u][mLOG]!=anc[v][mLOG]){
			u=anc[u][mLOG];
			v=anc[v][mLOG];
		}
		mLOG--;
	} 
	return anc[u][0];
}
int main(){
	cin>>n;
//	cout<<"n="<<n<<endl;
	for(int i=1;i<n;i++){
		cin>>anc[i][0];
		g[anc[i][0]].push_back(i);
//		cout<<"i="<<i<<endl;
	}
	dfs(0); 
//	for(int i=0;i<n;i++){
//		cout<<depth[i]<<" ";
//	}
//	cout<<endl;
//	
	cin>>q;
	while(q--){
		cin>>m;
		cin>>LCA;
		for(int i=1;i<m;i++){
			cin>>p;
			LCA=getLCA(p,LCA);
		}
		cout<<LCA<<endl;
	}
} 

回复

2 条回复,欢迎继续交流。

正在加载回复...