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 - 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 - 1130 Infix Expression(25 分)
PAT (Advanced Level) Practice - 1130 Infix Expression(25 分)
125 0
PAT (Advanced Level) Practice - 1030 Travel Plan(30 分)
PAT (Advanced Level) Practice - 1030 Travel Plan(30 分)
107 0
PAT (Advanced Level) Practice - 1122 Hamiltonian Cycle(25 分)
PAT (Advanced Level) Practice - 1122 Hamiltonian Cycle(25 分)
116 0
|
存储
PAT (Advanced Level) Practice - 1126 Eulerian Path(25 分)
PAT (Advanced Level) Practice - 1126 Eulerian Path(25 分)
137 0
PAT (Advanced Level) Practice - 1053 Path of Equal Weight(30 分)
PAT (Advanced Level) Practice - 1053 Path of Equal Weight(30 分)
124 0
PAT (Advanced Level) Practice - 1095 Cars on Campus(30 分)
PAT (Advanced Level) Practice - 1095 Cars on Campus(30 分)
130 0
PAT (Advanced Level) Practice - 1147 Heaps(30 分)
PAT (Advanced Level) Practice - 1147 Heaps(30 分)
118 0
PAT (Advanced Level) Practice - 1068 Find More Coins(30 分)
PAT (Advanced Level) Practice - 1068 Find More Coins(30 分)
112 0