题解 | 【模板】堆

【模板】堆

https://www.nowcoder.com/practice/13f61c8c92404f5ea5d6fa4c692869fb

#include <bits/stdc++.h>
using namespace std;
priority_queue<int> q;//开个stl大根堆

void show()//输出队首元素
{
    if(q.empty())cout << "empty" << endl;
    else cout << q.top() << endl;
}

int main()
{
    int n;cin >> n;
    for(int i=1;i<=n;i++)//循环n次输入
    {
        string s;cin >> s;
        if(s=="push")//根据字符串模拟一下就行
        {
            int x;cin >> x;
            q.push(x);
        }
        else if(s=="top")
        {
            show();
        }
        else if(s=="pop")
        {
            show();
            if(!q.empty())q.pop();
        }
    }
    //注意pop和输出top的时候要判断一下堆是否为空
    return 0;
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务