pat A1143 Lowest Common Ancestor(30 分)

//pat A1143 Lowest Common Ancestor(30 分)
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn=10010;

int pre[maxn];
int k,n;

int main(){
	scanf("%d%d",&k,&n);
	for(int i=0;i<n;i++){
		scanf("%d",&pre[i]);
	}
	int u,v;
	for(int q=0;q<k;q++){
		bool findU=false,findV=false;
		scanf("%d%d",&u,&v);
		int posU,posV;
		for(int i=0;i<n;i++){
			if(pre[i]==u){
				findU=true;
				posU=i;
			}
			if(pre[i]==v){
				findV=true;
				posV=i;
			}
		}
		if(findU==false&&findV==false){
			printf("ERROR: %d and %d are not found.\n",u,v);
			continue;
		}
		if(findU==false){
			printf("ERROR: %d is not found.\n",u);
			continue;
		}
		if(findV==false){
			printf("ERROR: %d is not found.\n",v);
			continue;
		}
		
		bool isSwap=false;//标记u,v是否交换过 
		if(u>v){
			swap(u,v);
			swap(posU,posV);
			isSwap=true;
		}
		int num=-1;
		for(int i=0;i<n;i++){
			if(pre[i]>u&&pre[i]<=v&&i<posV){//i欲成为v的祖先,在pre序列中,i必须在v之前 
				num=i;
				break;
			}
		}
		if(num!=-1){
			if(isSwap){//u,v交换过 
				swap(u,v);
			}
			printf("LCA of %d and %d is %d.\n",u,v,pre[num]);
		}
		else{
			if(posU>posV){
				swap(u,v);
			}
			printf("%d is an ancestor of %d.\n",u,v);
		} 
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38705851/article/details/82387888