动态中位数

 

 对顶堆的应用

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int main() {
 4     int t;
 5     cin >> t;
 6     while (t--) {
 7         int n, m;
 8         cin >> n >> m;
 9         cout << n << " " << (m + 1) / 2 << endl;
10         priority_queue<int, vector<int>, less<int> > down; //down为大根堆
11         priority_queue<int, vector<int>, greater<int> > up; //up为小根堆
12         int cnt = 0;
13         for (int i = 1; i <= m; i++) {
14             int x;
15             cin >> x;
16             if (down.empty() || x <= down.top()) {
17                 down.push(x);
18             } else {
19                 up.push(x);
20             }
21             if (down.size() > up.size() + 1) {
22                 up.push(down.top());
23                 down.pop();
24             }
25             if (up.size() > down.size()) {
26                 down.push(up.top());
27                 up.pop();
28             }
29             if (i % 2) {
30                 cout << down.top() << " ";
31                 cnt++;
32                 if (cnt % 10 == 0) {
33                     cout << endl;
34                 }
35             }
36         }
37         if (cnt % 10) { 
38             cout << endl;
39         }
40     }
41     return 0;
42 }

 

posted @ 2020-11-11 15:09  kyk333  阅读(158)  评论(0)    收藏  举报