版本比较
浅谈优先队列
正文
增加 24 行删除 24 行
15 行未改动16171819202120212223242521 行未改动474849505151525353545556572 行未改动606162636464656667686970707172737475757677787980808182838485868788888990909192939494959697987 行未改动1061071081091101101111121131141151151161171181191201211221231231241251251261271271281291301317 行未改动1391401411421431431441451461471481491491501511521534 行未改动15815916016116216216316416516655 行未改动2222232242252262262272282282292302312312322332332342352362372382392392402412422439 行未改动15 行未改动```
创建一个优先队列有两种情况:```cpppriority_queue<int,vector<int>,greater<int> >//小根堆 priority_queue<int,vector<int>,less<int> >//大根堆 priority_queue<int,vector<int>,greater<int> >//小根堆priority_queue<int,vector<int>,less<int> >//大根堆```
基础操作如下21 行未改动```cpp#include<bits/stdc++.h>using namespace std;
priority_queue<int,vector<int>,less<int> >q; priority_queue<int,vector<int>,less<int> >q;
//开个快读 //开个快读int inline read(){ int x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9')x=x*10+(ch-'0'),ch=getchar();2 行未改动
string s;
signed main(){ //输出优化 //输出优化 ios::sync_with_stdio(0); cout.tie(0); int t=read(); while(t--){ cin>>s; //1操作 //1操作 if(s=="push"){ int k=read(); q.push(k); } //2操作 //2操作 else if(s=="pop"){ if(!q.empty()) q.pop(); else continue; } //3操作 //3操作 else if(s=="top"){ if(q.size()==0){ cout<<"empty"; continue; } cout<<q.top()<<'\n'; } //4操作 //4操作 else if(s=="size") cout<<q.size(); //5操作 //5操作 else if(s=="clear"){ while(1){ if(q.empty()) break; //边界条件,防止RE //边界条件,防止RE else q.pop(); } } }7 行未改动剩余见代码注释:```cpp//P3887 [GDOI2014] 世界杯#include<bits/stdc++.h>#define int long long //开不开long long都可以 #define int long long //开不开long long都可以using namespace std;
priority_queue<int,vector<int> >q[5];//默认大根堆
//又开快读 //又开快读int inline read(){ int x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9')x=x*10+(ch-'0'),ch=getchar(); return x*f;}
signed main(){ signed main(){ int k=read(),d=read(),m=read(),f=read(); //输入 //输入 for(int i=1;i<=k;i++){ //先任意给定一个变量,然后再压入队列 //先任意给定一个变量,然后再压入队列 int x=read(); q[1].push(x); } for(int i=1;i<=d;i++){7 行未改动 for(int i=1;i<=f;i++){ int x=read(); q[4].push(x); } //询问 //询问 int p=read(); while(p--){ int a=read(),b=read(),c=read(); double ans=q[1].top(); q[1].pop(); //由于要求每次选择不得有以前选择的选手,那么弹出后就不用输回 //由于要求每次选择不得有以前选择的选手,那么弹出后就不用输回 for(int i=1;i<=a;i++){ ans+=q[2].top(); q[2].pop(); }4 行未改动 for(int i=1;i<=c;i++){ ans+=q[4].top(); q[4].pop(); } //小数保存两位输出 //小数保存两位输出 printf("%.2lf\n",ans/11); } return 0;}55 行未改动signed main(){ n=read(); for(int i=1;i<=n;i++){ int a=read(); //小根堆维护偶数 //小根堆维护偶数 if(i%2==0) q2.push(a); //大根堆维护奇数 //大根堆维护奇数 else q1.push(a); if((!q2.empty())&&q1.top()>q2.top()){ //存储最大的奇数和最小的偶数 //存储最大的奇数和最小的偶数 const int t1=q1.top(),t2=q2.top(); //交换压入 //交换压入 q2.pop(); q2.push(t1); q1.pop(); q1.push(t2); } //输出中位数 //输出中位数 if(i%2!=0) cout<<q1.top()<<'\n'; } return 0;}9 行未改动