3 solutions
-
2
题意
进行 次操作,加人或减人。减人时减数字最大的那个
思路
嗯,看到最大就想起了 sort,但是 sort 需要写结构体和排序函数,所以直接用简洁的优先队列。
优先队列有两个特点:
- 大的排前面
- 排结构体时按最前面的数据排
再推荐一个数据结构:元组。它可以存两个数据。写法
pair<数据结构1,数据结构2>
知道这些后,这题就很简单了吧
代码
#include <bits/stdc++.h> using namespace std; priority_queue<pair<int,string>> q; int main(int argc, char **argv){ int n; cin >> n; while(n--){ string op; cin >> op; if (op == "pop"){ if (q.empty()){ // 没人排队 printf("none\n"); continue; } // 有人就输出 cout << q.top().second; printf(" %d\n",q.top().first); q.pop(); }else{ // 新人 string s;int x; cin >> s >> x; q.push({x,s}); } } return 0; }
-
2
#include<iostream> #include<string> #include<queue> using namespace std; int n; struct node { string name; int bi; bool operator < (const node &a)const//重载运算符,用于优先队列的排序 { return bi<a.bi; } }; priority_queue<node>q;//优先队列 int main() { cin>>n; while(n--) { string s; cin>>s; if(s=="push")//push操作 { string na; int b; cin>>na>>b; q.push({na,b}); } if(s=="pop")//pop操作 { if(q.size())//判断是否为空 { cout<<q.top().name<<" "<<q.top().bi<<endl; q.pop(); } else { cout<<"none\n"; } } } return 0;//完结散花 }
-
0
#include<bits/stdc++.h> using namespace std; priority_queue<pair<int,string>>q; int main(){ int n; cin>>n; for(int i=1;i<=n;i++){ string a; cin>>a; if(a=="pop"){ if(q.empty()){ cout<<"none"<<endl; continue; } else{ cout<<q.top().second<<" "<<q.top().first<<endl; q.pop(); } } else{ string x; int y; cin>>x>>y; q.push({y,x}); } } }
- 1
Information
- ID
- 856
- Time
- 1000ms
- Memory
- 256MiB
- Difficulty
- 4
- Tags
- # Submissions
- 44
- Accepted
- 20
- Uploaded By