L2-012. 关于堆的判断(小顶堆)

来源:互联网 发布:淘宝卖家和买家都被骗 编辑:程序博客网 时间:2024/05/29 17:44

L2-012. 关于堆的判断

时间限制
400 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
陈越

将一系列给定数字顺序插入一个初始为空的小顶堆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 446 23 26 24 1024 is the root26 and 23 are siblings46 is the parent of 2323 is a child of 10
输出样例:
FTFT
//注意是一边建一边输入的
#include <bits/stdc++.h>using namespace std;#define maxn 1100int num[maxn];int flag;void adjust(int i, int n){    int l = i * 2, r = i * 2+1;    if(r <= n)    {        if(num[r] < num[l])        {            if(num[r] < num[i])            {                swap(num[r], num[i]);                flag = 1;            }        }        else if(num[l] < num[r])        {            if(num[l] < num[i])            {                swap(num[l], num[i]);                flag =1;            }        }    }    else if(l <= n)    {        if(num[l] < num[i])        {            swap(num[l], num[i]);            flag =1;        }    }}int main(){    int n, m;    scanf("%d%d", &n, &m);    for(int i = 1; i <= n; i++)    {        scanf("%d", &num[i]);        while(1)        {            flag = 0;            for(int j = i/2; j >= 1; j-- )            {                adjust(j, i);            }            if(!flag) break;        }    }    //for(int i = 1; i <= n; i++)    //printf("%d -- %d\n",num[i], i);    map<int, int>ma;    for(int i = 1; i <= n; i++)        ma[num[i]] = i;    int u, v;    int id1, id2;    char  str[1100],str1[1100];    while(m--)    {        scanf("%d", &u);        id1 = ma[u];        scanf("%s",str);        if(str[0] == 'a')        {            scanf("%d", &v);            gets(str1);            id2 = ma[v];            if(id1 != id2 && id1/2 == id2/2 )                puts("T");            else puts("F");        }        else        {            scanf("%s",str);            if(str[0] =='a')            {                scanf("%s%s%d",str,str1,&v);                id2 = ma[v];                if(id1/2 == id2)                    puts("T");                else puts("F");            }            else            {                scanf("%s",str);                if(str[0] == 'r')                {                    if(id1 == 1)                        puts("T");                    else puts("F");                }                else                {                    scanf("%s%d",str,&v);                    id2 = ma[v];                    if(id2/2 == id1)                        puts("T");                    else puts("F");                }            }        }    }}


0 0
原创粉丝点击