1151 LCA in a Binary Tree

#include<iostream>
#include<vector>
#include<map> 
using namespace std;
vector<int> pre,in;
map<int,int> pos;
void lca(int U,int V,int preRoot,int inL,int inR){
	if(inL>inR) return;
	int posU=pos[U],posV=pos[V],posRoot=pos[pre[preRoot]];
	int left=posRoot-inL;
	if(posU==posRoot)
		printf("%d is an ancestor of %d.\n",U,V);
	else if(posV==posRoot)
		printf("%d is an ancestor of %d.\n",V,U);
	else if(posU<posRoot&&posV<posRoot)
		lca(U,V,preRoot+1,inL,posRoot-1);
	else if(posU>posRoot&&posV>posRoot)
		lca(U,V,preRoot+left+1,posRoot+1,inR);
	else
		printf("LCA of %d and %d is %d.\n",U,V,pre[preRoot]);
}
int main(){
	int M,N,U,V;
	cin>>M>>N;
	pre.resize(N+1);
	in.resize(N+1); 
	for(int i=1;i<=N;i++){
		cin>>in[i];
		pos[in[i]]=i;//0用来标记是否存在 
	}
	for(int i=1;i<=N;i++) cin>>pre[i];
	for(int i=0;i<M;i++){
		cin>>U>>V;
		if(pos[U]==0&&pos[V]==0)
			printf("ERROR: %d and %d are not found.\n",U,V);
		else if(pos[U]==0&&pos[V]!=0)
			printf("ERROR: %d is not found.\n",U);
		else if(pos[V]==0&&pos[U]!=0)
			printf("ERROR: %d is not found.\n",V);
		else
			lca(U,V,1,1,N); 
	}
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/weixin_42820516/article/details/84771808
今日推荐