题目
题目跳转 1143 Lowest Common Ancestor (30 分)
分析
看到这道题首先想到的是构建好一颗BST然后查找两个节点的路径从尾部进行遍历找到第一个相同节点就是公共的最小节点。但是有一个点始终是超时的过不去。后来找了资料换了种思路,寻找两个点范围内的点[u,v]范围内,就是最小公共节点。
code
#include <iostream>
#include <stdio.h>
#include <map>
using namespace std;
const int M = 10010;
int nodes[M];
int checknum, nodenum, common;
int main()
{
cin >> checknum >> nodenum;
map<int, int> m;
for (int i = 0; i < nodenum; i++)
{
cin >> nodes[i + 1];
m[nodes[i + 1]] = i + 1;
}
for (int i = 0; i < checknum; i++)
{
int u, v, fu = 0, fv = 0;
cin >> u >> v;
fu = m[u];fv = m[v];
if (fu == 0 && fv == 0)
printf("ERROR: %d and %d are not found.\n", u, v);
else if(fu==0||fv==0)
printf("ERROR: %d is not found.\n", fu==0?u:v);
else {
for (int i = 1; i <= nodenum; i++)
{
// 找到最小节点
if(nodes[i]>=min(u,v)&&nodes[i]<=max(u,v)){
common = nodes[i]; break;
}
}
if(common==u||common==v){
printf("%d is an ancestor of %d.\n",common==u?u:v,common==v?u:v);
}else{
printf("LCA of %d and %d is %d.\n",u,v,common);
}
}
}
}