poj 3481 set 容器 银行 K P

来源:互联网 发布:淘宝店铺怎么装修 编辑:程序博客网 时间:2024/06/05 09:22

题意:输入1的时候 输入 K  P,输入2的时候找出最大的P对应的K,并删除这个P。输入3的时候找出最小的P对应的K,并删除P。输入2,3的时候如果没有P了,那么输出0.

思路:利用set 和 priority_queue

#include<iostream>#include<set>using namespace std;typedef struct {  int k,p;}settype;bool operator < (const settype &a,const settype &b){return a.p<b.p;}//因为STL中默认是以小于号来排序的,所以要重载小于号,如果a.p>b.p那么默认是以递减的顺序排的。int main(){  set<settype> Q;  set<settype>::iterator iter;  settype S;  int a;  while(scanf("%d",&a)!=EOF&&a)  {    if(a==0) break;    else if(a==1)    {      scanf("%d%d",&S.k,&S.p);      Q.insert(S);    }    else if(a==2)    {      if(!Q.empty())      {        iter=Q.end();//end返回的是最后一个元素的后面的位置,迭代器的值。        iter--;        S=*iter;        cout<<S.k<<endl;        Q.erase(*iter);      }      else cout<<"0"<<endl;    }    else if(a==3)    {      if(!Q.empty())      {        iter=Q.begin();        cout<<(*iter).k<<endl;        Q.erase(*iter);      }      else cout<<"0"<<endl;    }  }}

下面是用数组对应的K,但是内存开销相当大。

#include<iostream>#include<set>using namespace std;int a[10000010];int main(){  set<int> Q;  set<int>::iterator iter;  int t,p,k;  while(scanf("%d",&t)!=EOF&&t)  {    if(t==1)    {      scanf("%d%d",&k,&p);      a[p]=k;      Q.insert(p);    }    else if(t==2)    {      if(!Q.empty())      {        iter=Q.end();        iter--;        p=*iter;        cout<<a[p]<<endl;        Q.erase(p);      }      else cout<<"0"<<endl;    }    else if(t==3)    {      if(!Q.empty())      {        iter=Q.begin();        p=*iter;        cout<<a[p]<<endl;        Q.erase(p);      }      else cout<<"0"<<endl;    }  }}

这个是用的优先队列,貌似时间比前两个快啊

#include<iostream>#include<vector>#include<queue>using namespace std;long a[10000010];int main(){  long K,P;  priority_queue<long,vector<long>,greater<int> > L;  priority_queue<long,vector<long>,less<long> > H;  long t;  while(scanf("%ld",&t)!=EOF&&t)  {    if(t==1)    {      scanf("%ld %ld",&K,&P);      a[P]=K;      L.push(P);      H.push(P);      //system("pause");    }    else if(t==2)    {      if(!H.empty())      {        P=H.top();        while(!H.empty()&&a[P]==-1)        {          H.pop();          P=H.top();        }        if(!H.empty())        {          P=H.top();          cout<<a[P]<<endl;          a[P]=-1;        }        else cout<<"0"<<endl;      }      else cout<<"0"<<endl;    }    else if(t==3)    {      if(!L.empty())      {        P=L.top();        while(!L.empty()&&a[P]==-1)        {          L.pop();          P=L.top();        }        if(!L.empty())        {          P=L.top();          cout<<a[P]<<endl;          a[P]=-1;        }        else cout<<"0"<<endl;      }      else      cout<<"0"<<endl;    }  }}


原创粉丝点击