中位數_POJ3784_Running Median
阿新 • • 發佈:2018-12-18
思路分析:
使用兩個堆, 一個最大堆儲存當前較小的一半, 一個最小堆儲存當前較大的一半, 每讀入一個數
動態維護這兩個堆, 當以讀入奇數個數時, 輸出當前最大堆堆頂即可. 具體如下AC程式碼所示:
//POJ3784_Running Median #include <iostream> #include <cstdio> #include <algorithm> #include <functional> #include <queue> using namespace std; int main(){ int P; scanf("%d", &P); while(P--){ int sn, M; scanf("%d %d", &sn, &M); cout << sn << " " << M / 2 + 1 << endl; priority_queue<int, deque<int>, greater<int> > up; priority_queue<int> down;//始終維持down.size() >= up.size且up.size() >= down.size() - 1 for(int i = 1, t; i <= M; ++i){ scanf("%d", &t); if(i & 1){ if(up.empty()) down.push(t); else if(up.top() < t) down.push(up.top()), up.pop(), up.push(t); else down.push(t); cout << down.top() << " "; if(!((i + 1) % 20) || i == M) cout << endl; }else if(down.top() > t) up.push(down.top()), down.pop(), down.push(t); else up.push(t); } } return 0; }