这道题可以用堆实现,不过利用优先队列是更简单的方法(实际上,优先队列的底层实现就是二叉堆),需要注意结构体的比较符号的重载,下面的代码里给出了重载的两种方式:
#include<iostream>
#include<cstdio>
#include<queue>
#include<stdio.h>
#include<string>
using namespace std;
struct Complex
{
int x,y;
Complex(int x,int y):x(x),y(y){}
//重载比较符号
friend bool operator <(Complex a,Complex b)
{
if(a.x*a.x+a.y*a.y==b.x*b.x+b.y*b.y)
{
return a.y>b.y;
}
else
return a.x*a.x+a.y*a.y<b.x*b.x+b.y*b.y; //正常排序,值越大的排的越靠前
}
/*
//这种形式的重载也是可以的
bool operator<(Complex c)const{
return x*x+y*y<c.x*+c.x+c.y*c.y;
}
*/
};
priority_queue<Complex> q;
void Pop()
{
if(q.empty())
{
cout<<"empty "<<endl;
return;
}
else
{
Complex c=q.top();
cout<<c.x<<"+i"<<c.y<<endl;
q.pop();
cout<<"SIZE = "<<q.size()<<endl;
}
return;
}
void Insert(int a,int b)
{
Complex c=Complex(a,b);
q.push(c);
cout<<"SIZE = "<<q.size()<<endl;
return;
}
int main()
{
int n,x,y;
char str2[1001]={};
string str;
while(cin>>n)
{
while(!q.empty())
q.pop();
for(int i=0;i<n;i++)
{
//读取指令
cin>>str;
if(str=="Pop")
Pop();
else if(str=="Insert")
{
scanf("%d+i%d",&x,&y);
Insert(x,y);
}
}
}
return 0;
}
京公网安备 11010502036488号