PAT 1143 Lowest Common Ancestor
The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U and V as descendants. A binary search tree (BST) is recursively defined as a binary tree which has the following properties: The left subtree of a node contains only nodes with keys less than the node‘s key. Input Specification: Output Specification: Sample Input:
Sample Output:
#include <iostream> #include <vector> #include <map> using namespace std; map<int,bool> mp; int main() { int m,n,u,v,a; scanf("%d %d",&m,&n); vector<int> pre(n); for (int i = 0; i < n; i++) { scanf("%d",&pre[i]); mp[pre[i]] = true; } for (int i = 0; i < m; i++) { scanf("%d %d",&u,&v); for(int j = 0; j < n; j++) { a = pre[j]; if ((a > u && a < v)|| (a > v && a < u) || (a == u) || (a == v)) break; } if (mp[u] == false && mp[v] == false) printf("ERROR: %d and %d are not found.n",v); else if (mp[u] == false || mp[v] == false) printf("ERROR: %d is not found.n",mp[u] == false ? u : v); else if (a == u || a == v) printf("%d is an ancestor of %d.n",a,a == u ? v : u); else printf("LCA of %d and %d is %d.n",a); } return 0; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |