【PTA L2-012】关于堆的判断(堆的建立和特殊字符串的读入)

版权声明:转载请注明出处哦~ https://blog.csdn.net/Cassie_zkq/article/details/88917920

题目地址:https://pintia.cn/problem-sets/994805046380707840/problems/994805064676261888

题目:


解题思路:


注意是一边读入一边建堆!!向上寻找合适的位置放当前值

字符串的读入stringstream和sscanf的用法,以及map的使用。若这样写超时的话就一边读字符串一边判断接下来还要读几个字符串

ac代码:


#include <iostream>
#include <algorithm>
#include <string.h>
#include <ctype.h>
#include <set>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <sstream>
#define  maxn 1005
typedef long long ll;
const ll inf=99999999;
using namespace std;
int h[maxn],n,m,x,a,b;
string s[20],s1,s2;
map<int,int> f;
void build(int t)//创建小顶堆
{
    int temp=h[t],c=t,p=t>>1;//s=child,p=parent
    while(c>1&&h[p]>temp)
    {
        h[c]=h[p];//把值大的父亲不断移下来,为temp找到合适的位置
        c=p;
        p>>=1;
    }
    h[c]=temp;
}
int main()
{
    //freopen("/Users/zhangkanqi/Desktop/11.txt","r",stdin);
    scanf("%d %d",&n,&m);
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&h[i]);
        build(i);
    }
    getchar();//注意读取换行符,否则第一个字符床读入的是换行符,结果错误
    for(int i=1;i<=n;i++)
    {
        f[h[i]] = i;
    }
    while(m--)
    {
        getline(cin, s1);
        if (s1.find("root") != string::npos) {
            sscanf(s1.c_str(), "%d", &x);
            if (f[x] == 1)
                printf("T\n");
            else printf("F\n");
        } else {
            int num = 0;
            stringstream ss(s1);//定义流,如果放在外层定义的话记得每次用完都要清空一次,ss.clear()
            while (ss >> s2)
                s[num++] = s2;
            if (s1.find("siblings") != string::npos) {
                sscanf(s[0].c_str(), "%d", &a);
                sscanf(s[2].c_str(), "%d", &b);
                if (f[a] / 2 == f[b] / 2)
                    printf("T\n");
                else printf("F\n");
            } else if (s1.find("parent") != string::npos) {
                sscanf(s[0].c_str(), "%d", &a);
                sscanf(s[5].c_str(), "%d", &b);
                if (f[b] / 2 == f[a])
                    printf("T\n");
                else printf("F\n");
            } else if (s1.find("child") != string::npos) {
                sscanf(s[0].c_str(), "%d", &a);
                sscanf(s[5].c_str(), "%d", &b);
                if (f[a] / 2 == f[b])
                    printf("T\n");
                else printf("F\n");
            }
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Cassie_zkq/article/details/88917920
今日推荐