题解 | #复数集合#
复数集合
https://www.nowcoder.com/practice/abdd24fa839c414a9b83aa9c4ecd05cc
#include <iostream> #include <cstdio> #include <queue> #include <string> using namespace std; struct Complex { //复数 int real; //实部 int imaginary; //虚部 }; bool operator < (Complex c1, Complex c2) { //运算符重载 if (c1.imaginary * c1.imaginary + c1.real * c1.real < c2.real * c2.real + c2.imaginary * c2.imaginary) { //左边的模比右边的要小,则交换 return true; } else if (c1.imaginary * c1.imaginary + c1.real * c1.real == c2.real * c2.real + c2.imaginary * c2.imaginary && c1.imaginary > c2.imaginary) { //模相等但左边虚部大于右边虚部, 也要交换 return true; } return false; } int main() { int n; scanf("%d", &n); priority_queue<Complex> priorityQueue; //优先级队列,默认大根堆 char words[20]; //Pop Insert操作 string wordStr; for (int i = 0; i < n; i++) { scanf("%s", words); wordStr = words; //转换成C++风格后面好比较 if (wordStr == "Pop") { if (priorityQueue.empty()) { printf("empty\n"); } else { Complex complex = priorityQueue.top(); priorityQueue.pop(); printf("%d+i%d\n", complex.real, complex.imaginary); printf("SIZE = %d\n", priorityQueue.size()); } } else { Complex complex; int real; int imaginary; scanf("%d+i%d", &real, &imaginary); //格式化读取,怎么输入就怎么读 complex.real = real; complex.imaginary = imaginary; priorityQueue.push(complex); printf("SIZE = %d\n", priorityQueue.size()); } } }