题解 | #Median#
Median
https://www.nowcoder.com/practice/b5da3f56557f42978ca87afedbd85fbe
#include <bits/stdc++.h> #include <queue> using namespace std; int main() { int a; while (cin >> a) { // 注意 while 处理多个 case priority_queue<long> maxheap; priority_queue<long, vector<long>, greater<>> minheap; long t, b; while (a--) { cin >> t; if (maxheap.empty() || t <= maxheap.top()) maxheap.push(t); else minheap.push(t); while (maxheap.size() > minheap.size() + 1) { minheap.push(maxheap.top()); maxheap.pop(); } while (maxheap.size() < minheap.size()) { maxheap.push(minheap.top()); minheap.pop(); } } cin>>b; while (b--) { cin >> t; if (maxheap.empty() || t <= maxheap.top()) maxheap.push(t); else minheap.push(t); while (maxheap.size() > minheap.size() + 1) { minheap.push(maxheap.top()); maxheap.pop(); } while (maxheap.size() < minheap.size()) { maxheap.push(minheap.top()); minheap.pop(); } } cout<<maxheap.top()<<endl; // cout<<endl<<maxheap.size()<<' '<<maxheap.top()<<endl; // cout<<endl<<minheap.size()<<' '<<minheap.top()<<endl; } } // 64 位输出请用 printf("%lld")
堆解法