使用priority_queue,并且重载运算符就可以。但是要注意优先队列是大根堆。和sort是相反的。
#include<iostream> #include<math.h> #include<queue> using namespace std; struct complex { int a;int b; inline bool operator < (const complex &c)const{ if((a*a+b*b)==(c.a*c.a+c.b*c.b)){ return c.b>b; }return (a*a+b*b)<(c.a*c.a+c.b*c.b); } }; int main() { int n; string s; while(cin>>n){ getchar(); priority_queue<complex> q; complex c; for(int i=0;i<n;i++){ getline(cin,s); //cout<<s<<endl; if(s[0]=='P'){ if(q.empty()) printf("empty\n"); else{ c=q.top();q.pop(); printf("%d+i%d\n",c.a,c.b); printf("SIZE = %d\n",q.size()); } }else if(s[0]=='I'){ int pos=s.find(" ")+1; int num=0; while(s[pos]>='0'&&s[pos]<='9'){ num=num*10+s[pos]-'0'; pos++; } c.a=num; pos+=2; num=0; while(s[pos]>='0'&&s[pos]<='9'){ num=num*10+s[pos]-'0'; pos++; } c.b=num; q.push(c); printf("SIZE = %d\n",q.size()); } } } return 0; }