1143 Lowest Common Ancestor

#include<iostream> 
#include<vector>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map> 
using namespace std;
vector<int> pre;
vector<int> in;
struct node{
	int value;
	node* left;
	node* right;
};
node* buildtree(int prel,int prer,int inl,int inr){
	if(prel>prer) return 0;
	node* root=new node;
	root->value=pre[prel];
	root->left=NULL;
	root->right=NULL;
	int k;
	for(k=inl;k<=inr;k++){
		if(pre[prel]==in[k]){
			break;
		}
	}
	int numleft=k-inl;//左子树节点个数
	root->left=buildtree(prel+1,prel+numleft,inl,k-1);
	root->right=buildtree(prel+numleft+1,prer,k+1,inr);
	return root; 
}
void findfa(int a,int b,node* tree){
	if(tree==NULL) return;
	if(tree->value==a||tree->value==b){
		a=tree->value==a?a:b;
		printf("%d is an ancestor of %d.\n",a,b);
		return;
	}else if((tree->value>a&&tree->value<b)||(tree->value<a&&tree->value>b)){
		printf("LCA of %d and %d is %d.\n",a,b,tree->value);
		return;
	}else{
		findfa(a,b,tree->right);
		findfa(a,b,tree->left);
	}
}
int main()
{
	#ifdef ONLINE_JUDGE
	#else
	freopen("in.txt","r",stdin);
	#endif
	int n,m;
	cin>>m>>n;
	map<int,int> hash;
	for(int i=0;i<n;i++){
		int temp;
		cin>>temp;
		pre.push_back(temp);
		hash[temp]++;
	}
	//memcpy(in,pre,sizeof(int)*pre.size());
	in.assign(pre.begin(),pre.end());
	sort(in.begin(),in.end());
	node* root=buildtree(0,n-1,0,n-1);
	for(int i=0;i<m;i++){
		int u,v;
		cin>>u>>v;
		if(hash[u]==0&&hash[v]==0) printf("ERROR: %d and %d are not found.\n",u,v);
		else if(hash[u]==0||hash[v]==0){
			u=(hash[u]==0?u:v);
			printf("ERROR: %d is not found.\n",u);
		}else{
			findfa(u,v,root);
		}
	}
	return 0;
}

第四个测试点通不过,跪求大佬检查??

猜你喜欢

转载自blog.csdn.net/csg3140100993/article/details/81355527