PAT (Advanced Level) Practice - 1143 Lowest Common Ancestor(30 分)

简介: PAT (Advanced Level) Practice - 1143 Lowest Common Ancestor(30 分)

题目链接:点击打开链接

题目大意:给出一棵二叉搜索树的前序遍历,问结点u和v的共同最低祖先是谁。

解题思路:用ump记录下访问节点,遍历一遍pre数组(因为每一个都是“根”)而且是BST树,将当前结点标记为a,如果u和v分别在a的左、右,或者u、v其中一个就是当前a,即(a >= u && a <= v) || (a >= v && a <= u),说明找到了这个共同最低祖先a,退出当前循环。(第一个找到就退出循环,可以看下这棵树的图就明白了)


AC 代码

#include<bits/stdc++.h>#include<cmath>#define mem(a,b) memset(a,b,sizeof a)#define ssclr(ss) ss.clear(), ss.str("")#define INF 0x3f3f3f3f#define MOD 1000000007usingnamespacestd;
typedeflonglongll;
unordered_map<int,int>ump;
intmain()
{
intq,n,a,u,v,pre[10009];
scanf("%d%d",&q,&n);
for(inti=0;i<n;i++) scanf("%d",&pre[i]), ump[pre[i]]=1;
while(q--)
    {
scanf("%d%d",&u,&v);
for(inti=0;i<n;i++)
        {
a=pre[i];
if(a>=u&&a<=v||a>=v&&a<=u) break;
        }
if(ump[u]==0&&ump[v]==0) printf("ERROR: %d and %d are not found.\n",u,v);
elseif(ump[u]==0||ump[v]==0) printf("ERROR: %d is not found.\n",ump[u]==0?u:v);
elseif(a==u||a==v) printf("%d is an ancestor of %d.\n",a,a==u?v:u);
elseprintf("LCA of %d and %d is %d.\n",u,v,a);
    }
return0;
}
目录
相关文章
PAT (Advanced Level) Practice - 1119 Pre- and Post-order Traversals(30 分)
PAT (Advanced Level) Practice - 1119 Pre- and Post-order Traversals(30 分)
122 0
PAT (Advanced Level) Practice - 1119 Pre- and Post-order Traversals(30 分)
PAT (Advanced Level) Practice - 1127 ZigZagging on a Tree(30 分)
PAT (Advanced Level) Practice - 1127 ZigZagging on a Tree(30 分)
122 0
PAT (Advanced Level) Practice - 1060 Are They Equal(25 分)
PAT (Advanced Level) Practice - 1060 Are They Equal(25 分)
102 0
PAT (Advanced Level) Practice - 1122 Hamiltonian Cycle(25 分)
PAT (Advanced Level) Practice - 1122 Hamiltonian Cycle(25 分)
117 0
PAT (Advanced Level) Practice - 1004 Counting Leaves(30 分)
PAT (Advanced Level) Practice - 1004 Counting Leaves(30 分)
109 0
|
存储
PAT (Advanced Level) Practice - 1126 Eulerian Path(25 分)
PAT (Advanced Level) Practice - 1126 Eulerian Path(25 分)
138 0
PAT (Advanced Level) Practice - 1087 All Roads Lead to Rome(30 分)
PAT (Advanced Level) Practice - 1087 All Roads Lead to Rome(30 分)
99 0
PAT (Advanced Level) Practice - 1053 Path of Equal Weight(30 分)
PAT (Advanced Level) Practice - 1053 Path of Equal Weight(30 分)
126 0
PAT (Advanced Level) Practice - 1030 Travel Plan(30 分)
PAT (Advanced Level) Practice - 1030 Travel Plan(30 分)
111 0
PAT (Advanced Level) Practice - 1130 Infix Expression(25 分)
PAT (Advanced Level) Practice - 1130 Infix Expression(25 分)
125 0