题解 | #复数集合#
复数集合
https://www.nowcoder.com/practice/abdd24fa839c414a9b83aa9c4ecd05cc
主要考察了优先队列,注意优先队列的使用、运算符重载来比较结构体、添加cmath头文件、和各种细节
#include <queue> #include <cstdio> #include <iostream> #include <string> #include <cmath> //求次幂,是pow,不是power using namespace std; struct Complex{ int real; int unreal; int mo; Complex(int a, int b):real(a),unreal(b),mo(pow(a,2)+pow(b,2)){} }; bool operator < (Complex left, Complex right){ //return left.real*left.real + left.unreal*left.unreal < right.real*right.real + right.unreal*right.unreal; //这里运算符重载是因为结构体,另外因为是用大根堆,所以仍是<时触发交换,>时是小根堆 return left.mo < right.mo; } int main(){ int n; while(scanf("%d",&n)!=EOF){ priority_queue<Complex> myPriorityQueue;//注意定义的位置 for(int i = 0;i < n;i++){ //这里调试好几次才找到错误,用getline好像不会跳过开头的分隔符,故改为直接用cin string str; cin>>str; if(str == "Pop"){ //操作为pop时 if(myPriorityQueue.empty()){ printf("empty\n"); } else{ Complex ccur = myPriorityQueue.top(); printf("%d+i%d\n",ccur.real,ccur.unreal); myPriorityQueue.pop(); printf("SIZE = %d\n",myPriorityQueue.size()); } } else{ //操作为insert时,还要继续输入l+i2 int a1,b1; //这里的输入方法,按部就班用scanf就好,会跳过前面空格 scanf("%d+i%d",&a1,&b1); Complex ccur(a1,b1); //这里使用了构造函数,所以下面2行不用了 //ccur.real = a1; //ccur.unreal = b1; myPriorityQueue.push(ccur); printf("SIZE = %d\n",myPriorityQueue.size()); } } } }