L2-012. 关于堆的判断

L2-012. 关于堆的判断

题目链接:https://www.patest.cn/contests/gplt/L2-012

终于ac了,简直要哭。题目还是很简单的,不过很多坑:

1.寻找x下标时,有可能返回0,即x是根结点;

2.字符串中字符的位置有可能会因串中的数字长度大小改变而改变(QAQ找了一个小时才发现是在这里);

3.gets(函数)会读取前一个分隔符(是我基础不好╮(╯▽╰)╭).

代码如下:

#include<cstdio>
#include<iostream>
using namespace std;
int a[1005];
int location(int key){
    int k=0;
    while(a[k]!=key)k++;
    return k;
}
int transint(char s[]){
    if(s[0]=='-'){
        int temp=0;
        for(int i=1;s[i]!=' '&&s[i]!='';i++)
            temp=temp*10+s[i]-'0';
        return -temp;
    }else{
        int temp=0;
        for(int i=0;s[i]!=' '&&s[i]!='';i++)
            temp=temp*10+s[i]-'0';
        return temp;
    }
}
int main(void){
    int n,m;
    scanf("%d%d",&n,&m);
    for(int i=0;i<n;i++){
        scanf("%d",a+i);
        int k=i;
        while(k&&a[k]<a[(k-1)/2]){
            swap(a[k],a[(k-1)/2]);
            k=(k-1)/2;
        }
    }
    while(m--){
        bool flag;
        char s[50];
        int x;
        scanf("%d",&x);
        gets(s);//由于gets会读取x后的分隔符,所以字符串s实际上是从' '开始的
        //一开始用s[8]区分,发现第二种查询会因数字长度改变而改变
        if(s[4]=='t'&&s[8]=='r'){//第一种查询
            if(a[0]==x)flag=1;
            else flag=0;
        }else if(s[4]==' '){//第二种查询
            int y=transint(&s[5]);
            int t=location(x);
            if(t){
                if(t&1){
                    if(a[t+1]==y)flag=1;
                    else flag=0;
                }else{
                    if(a[t-1]==y)flag=1;
                    else flag=0;
                }
            }else flag=0;
        }else if(s[4]=='t'&&s[8]=='p'){//第三种查询
            int y=transint(&s[18]);
            int t=location(y);
            if(t&&a[(t-1)/2]==x)flag=1;
            else flag=0;
        }else if(s[4]=='a'){//第四种查询
            int y=transint(&s[15]);
            int t=location(x);
            if(t&&a[(t-1)/2]==y)flag=1;
            else flag=0;
        }
        if(flag)printf("T
");
        else printf("F
");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/barrier/p/5559751.html