1151 LCA in a Binary Tree (30 分)
#include <iostream>
#include <map>
using namespace std;
map<int, int> m;
int pre[10010], in[10010], n, M, x, y;
void dfs(int root, int l1, int l2) {
if(l1 > l2) return;
int proot = m[pre[root]], px = m[x], py = m[y];
if(px < proot && py < proot)
dfs(root + 1, l1, proot - 1);
else if(px < proot && py > proot || px > proot && py < proot)
printf("LCA of %d and %d is %d.\n", x, y, pre[root]);
else if(px > proot && py > proot)
dfs(root + proot - l1 + 1, proot + 1, l2);
else if(px == proot)
printf("%d is an ancestor of %d.\n", x, y);
else if(py == proot)
printf("%d is an ancestor of %d.\n", y, x);
}
int main() {
cin >> M >> n;
for(int i = 1; i <= n; ++i){
cin >> in[i];
m[in[i]] = i;
}
for(int i = 1; i <= n; ++i)
cin >> pre[i];
while(M--) {
cin >> x >> y;
if(m[x] == 0 && m[y] == 0)
printf("ERROR: %d and %d are not found.\n", x, y);
else if(m[x] == 0 || m[y] == 0)
printf("ERROR: %d is not found.\n", m[x] == 0 ? x : y);
else
dfs(1, 1, n);
}
}