本题思路很简单,借助重载运算符和优先队列,我们可以很容易的将输入的复数进行从大到小排列并输出,每次根据具体情况决定打印顺序即可。主要应该关注重载运算符和构造函数的使用,以及优先队列隐含的数据类型必须支持小于运算符的思想。重载运算符也是把大根堆变成小根堆的方式之一
#include <bits/stdc++.h>
using namespace std;
struct Complex { //结构体定义,复数可表示为a+bi
int a;
int b;
Complex(int _a,int _b){ //构造函数
a = _a;
b = _b;
}
};
bool operator < (Complex lhs,Complex rhs){ //运算符重载
if(lhs.a*lhs.a+lhs.b*lhs.b < rhs.a*rhs.a+rhs.b*rhs.b){
return true;
}
else{
return false;
}
}
int main() {
int n;
scanf("%d",&n);
char arr[10];
priority_queue<Complex> Myqueue;
for(int i = 0;i<n;i++){
scanf("%s",arr);
if(arr[0]=='P'){
if(!Myqueue.empty()){
printf("%d+i%d\n",Myqueue.top().a,Myqueue.top().b);
Myqueue.pop();
printf("SIZE = %d\n",Myqueue.size());
}
else{
printf("empty\n");
}
}
else{
Complex n = Complex(0, 0);
scanf("%d+i%d",&n.a,&n.b);
Myqueue.push(n);
printf("SIZE = %d\n",Myqueue.size());
}
}
return 0;
}



京公网安备 11010502036488号