题解 | 结构体优先队列

结构体优先队列

https://www.nowcoder.com/practice/e3d68ce7184e4658b42740edd4308d51

#include<bits/stdc++.h>
using namespace std;

//本题类似的题目其实在结构体那块写过,只是这里多了单科判断
//只需要重载运算符就好了
struct node{
    int chinese, math, english, sum;
};

bool operator<(node a, node b){
    // TODO: 实现比较逻辑,按照总分、语文、数学、英语的优先级排序
    if(a.sum!=b.sum)
    return a.sum<b.sum;//首先判断总分
    if(a.chinese!=b.chinese)
    return a.chinese<b.chinese;//总分相等比较语文
    if(a.math!=b.math)
    return a.math<b.math;//语文相等比数学
    return a.english<b.english;//直接比英语,不要再有if ,否则英语也相等就会没有返回值导致报错
}

priority_queue<node> s;
void insertValue(int chinese, int math, int english){
    // TODO: 实现插入操作
    s.push({chinese,math,english,chinese+math+english});//插入操作
}

void deleteValue(){
    // TODO: 实现删除操作
    if(!s.empty())//删除操作
    s.pop();
}

node getTop(){
    // TODO: 返回成绩最好的学生
    if(!s.empty())
    return s.top();//如果非空则返回队首
    else
    return {};//否则返回空节点
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    int q,op;
    int x, y, z;
    cin>>q;
    while(q--){
        cin>>op;
        if(op==1){
            cin>>x>>y>>z;
            insertValue(x, y, z);
        }
        if(op==2){
            node tmp = getTop();
            cout<<tmp.chinese<<" "<<tmp.math<<" "<<tmp.english<<endl;
        }
        if(op==3){
           deleteValue();
        }
    }
    return 0;
}

全部评论

相关推荐

点赞 评论 收藏
分享
饿魔:看到在线简历了吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务