106. 動態中位數
阿新 • • 發佈:2022-04-03
題目連結
106. 動態中位數
動態維護中位數問題:依次讀入一個整數序列, 每當已經讀入的整數個數為奇數 時, 輸出已讀入的整數構成的序列的中位數。
解題思路
對頂堆
維護兩個堆:大根堆:維護前 \(n/2\) 小數,小根堆:維護後 \(n-n/2\) 大數,遇到奇數個數時,小根堆堆頂即為所求
- 時間複雜度:\(O(nlogn)\)
程式碼
// Problem: 動態中位數 // Contest: AcWing // URL: https://www.acwing.com/problem/content/108/ // Memory Limit: 256 MB // Time Limit: 1000 ms // // Powered by CP Editor (https://cpeditor.org) // %%%Skyqwq #include <bits/stdc++.h> //#define int long long #define help {cin.tie(NULL); cout.tie(NULL);} #define pb push_back #define fi first #define se second #define mkp make_pair using namespace std; typedef long long LL; typedef pair<int, int> PII; typedef pair<LL, LL> PLL; template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; } template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; } template <typename T> void inline read(T &x) { int f = 1; x = 0; char s = getchar(); while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); } while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar(); x *= f; } priority_queue<int> q1; priority_queue<int,vector<int>,greater<int>> q2; int t,n; int main() { scanf("%d",&t); for(int i=1;i<=t;i++) { scanf("%*d%d",&n); printf("%d %d\n",i,(n+1)/2); while(q1.size())q1.pop(); while(q2.size())q2.pop(); int cnt=0; for(int j=1;j<=n;j++) { int x; scanf("%d",&x); if(q2.size()==0) q2.push(x); else if(q1.size()<q2.size()) { if(x>q2.top()) { int t=q2.top(); q2.pop(); q1.push(t); q2.push(x); } else q1.push(x); } else { if(x<q1.top()) { int t=q1.top(); q1.pop(); q2.push(t); q1.push(x); } else q2.push(x); } if(j&1) { printf("%d ",q2.top()); cnt++; if(cnt%10==0)puts(""); } } if(cnt%10!=0)puts(""); } return 0; }