不用建树!不用建树!!基本上碰到求LCA的都可以这么做出来。
#include<iostream>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
int m, n,temp,u,v;
int main() {
cin >> m >> n;
map<int, int> has;
for (int i = 1; i <= n; i++) {
scanf("%d", &temp);
has[temp] = i;
}
vector<int> pre(n+1);
for (int i = 1; i <= n; i++) scanf("%d",&pre[i]);
for (int i = 0; i < m; i++) {
scanf("%d %d",&u,&v);
if (!has[u] && !has[v]) printf("ERROR: %d and %d are not found.\n",u,v);
else if (has[u] && !has[v]) printf("ERROR: %d is not found.\n",v);
else if (!has[u] && has[v])printf("ERROR: %d is not found.\n",u);
else {
int j = 1;
for (; j <= n; j++) if (has[pre[j]] <= max(has[u],has[v]) && has[pre[j]] >= min(has[u], has[v]))break;
if (pre[j] == u) printf("%d is an ancestor of %d.\n",u,v);
else if (pre[j] == v)printf("%d is an ancestor of %d.\n", v, u);
else printf("LCA of %d and %d is %d.\n", u, v,pre[j]);
}
}
return 0;
}