题解 | #复数集合# 小根堆,大根堆的应用
复数集合
https://www.nowcoder.com/practice/abdd24fa839c414a9b83aa9c4ecd05cc
#include <cstdio> #include <iostream> #include <queue> #include <string> #include <vector> using namespace std; int n; struct Complex{ int real; int imag; }; bool operator < (Complex a, Complex b) { return a.real * a.real + a.imag * a.imag < b.real * b.real + b.imag * b.imag; } int main() { while(scanf("%d", &n) != EOF) { priority_queue<Complex> my; //优先队列默认是大根堆,小根堆为priority_queue<Complex, vector<Complex>, greater<Complex>> my, 注意在定义小根堆时要重载运算符 > 而不是 < for(int i = 0; i < n; i++) { char action[30]; scanf("%s", action); string action1 = action; if(action1 == "Pop") { if(my.empty()) puts("empty"); else { printf("%d+i%d\n", my.top().real, my.top().imag); my.pop(); printf("SIZE = %d\n", my.size()); } } else if(action1 == "Insert") { int re, im; scanf("%d+i%d", &re, &im); Complex com; com.real = re, com.imag = im; my.push(com); printf("SIZE = %d\n", my.size()); } } } }