1151开心34行代码搞定

#include 
#include 
#include 
#include 
using namespace std;
int pre[10010],in[10010];
map mp;
mapf;
int main()
{
	int m,n,u,v,a;
	scanf("%d %d",&m,&n);
	for(int i = 0; i < n; i++) {
		scanf("%d",&in[i]);
		mp[in[i]] = i;
		f[in[i]] = true;
	}
	for(int i = 0; i < n; i++) scanf("%d",&pre[i]);
	for(int i = 0; i < m; i++){
		scanf("%d %d",&u,&v);
		int j;
		for(j = 0; j < n; j++){
			a = mp[pre[j]];
			if((mp[u] >= a && mp[v] <=a) || (mp[u] <= a && mp[v] >= a)){
				break;
			}
		}
		if(f[u] == false && f[v] == false) printf("ERROR: %d and %d are not found.\n",u,v);
		else if(f[u] == false || f[v] == false) printf("ERROR: %d is not found.\n",f[v] == false?v:u);
		else if(mp[u] == a || mp[v] == a) printf("%d is an ancestor of %d.\n",pre[j],mp[v] == a?u:v);
		else printf("LCA of %d and %d is %d.\n",u,v,pre[j]);	
	}
	return 0;
}

 

你可能感兴趣的:(1151开心34行代码搞定)