题目链接:https://www.patest.cn/contests/gplt/L2-012
题目:
将一系列给定数字顺序插入一个初始为空的小顶堆H[]。随后判断一系列相关命题是否为真。命题分下列几种:
- “x is the root”:x是根结点;
- “x and y are siblings”:x和y是兄弟结点;
- “x is the parent of y”:x是y的父结点;
- “x is a child of y”:x是y的一个子结点。
输入格式:
每组测试第1行包含2个正整数N(<= 1000)和M(<= 20),分别是插入元素的个数、以及需要判断的命题数。下一行给出区间[-10000, 10000]内的N个要被插入一个初始为空的小顶堆的整数。之后M行,每行给出一个命题。题目保证命题中的结点键值都是存在的。
输出格式:
对输入的每个命题,如果其为真,则在一行中输出“T”,否则输出“F”。
输入样例:5 4
46 23 26 24 10
24 is the root
26 and 23 are siblings
46 is the parent of 23
23 is a child of 10
输出样例:
F
T
F
T
题解:自上而下建堆(自下而上建的堆不行,两者建出的堆不一样),然后根据秩的关系判断即可。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAX=1000+10;
int heap[MAX];
int N,M;
void percolateDown(int i)
{
int tmp=heap[i];
int father=i,child;
while((child=father<<1)<=N)
{
if(child+1<=N&&heap[child]>heap[child+1]) child++;
if(tmp<heap[child]) break;
heap[father]=heap[child];
father=child;
}
heap[father]=tmp;
}
void percolateUp(int i)
{
int tmp=heap[i];
while((i>>1)>=1&&tmp<heap[i>>1])
{
heap[i]=heap[i>>1];
i=(i>>1);
}
heap[i]=tmp;
}
void buildHeap()
{
/* for(int i=(N>>1);i>=1;i--)
{
percolateDown(i);
}*/
for(int i=2;i<=N;i++)
{
percolateUp(i);
}
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
while(scanf("%d%d",&N,&M)!=EOF)
{
for(int i=1;i<=N;i++)
scanf("%d",&heap[i]);
buildHeap();
/* for(int i=1;i<=N;i++)
printf("%d ",heap[i]);
printf("\n");
*/
getchar();
while(M--)
{
string mod;
getline(cin,mod);
const char *s=mod.data();
if(mod.find("root")!=string::npos)
{
int root;
sscanf(s,"%d is the root",&root);
printf("%s\n",heap[1]==root?"T":"F");
}
else if(mod.find("siblings")!=string::npos)
{
int a,b;
sscanf(s,"%d and %d are siblings",&a,&b);
int flag=0;
for(int i=1;i<=(N>>1);i++)
{
int lch=i<<1;
int rch=(i<<1)+1;
if((rch<=N&&heap[lch]==a&&heap[rch]==b)||(rch<=N&&heap[lch]==b&&heap[rch]==a))
{
flag=1;
break;
}
}
printf("%s\n",flag?"T":"F");
}
else if(mod.find("parent")!=string::npos)
{
int a,b;
sscanf(s,"%d is the parent of %d",&a,&b);
int flag=0;
for(int i=1;i<=(N>>1);i++)
{
int lch=i<<1;
int rch=(i<<1)+1;
if((heap[i]==a&&heap[lch]==b)||(rch<=N&&heap[i]==a&&heap[rch]==b))
{
flag=1;
break;
}
}
printf("%s\n",flag?"T":"F");
}
else if(mod.find("child")!=string::npos)
{
int a,b;
sscanf(s,"%d is a child of %d",&a,&b);
int flag=0;
for(int i=1;i<=(N>>1);i++)
{
int lch=i<<1;
int rch=(i<<1)+1;
if((heap[lch]==a&&heap[i]==b)||(rch<=N&&heap[rch]==a&&heap[i]==b))
{
flag=1;
break;
}
}
printf("%s\n",flag?"T":"F");
}
}
}
return 0;
}