您的位置:首页 > 其它

POJ 3784 Running Median( 堆优化

2018-03-10 20:50 134 查看

Running Median

题目描述

For this problem, you will write a program that reads in a sequence of 32-bit signed integers. After each odd-indexed value is read, output the median (middle value) of the elements received so far.

输入

The first line of input contains a single integer P, (1 ≤ P ≤ 1000), which is the number of data sets that follow. The first line of each data set contains the data set number, followed by a space, followed by an odd decimal integer M, (1 ≤ M ≤ 9999), giving the total number of signed integers to be processed. The remaining line(s) in the dataset consists of the values, 10 per line, separated by a single space. The last line in the dataset may contain less than 10 values.

输出

For each data set the first line of output contains the data set number, a single space and the number of medians output (which should be one-half the number of input values plus one). The output medians will be on the following lines, 10 per line separated by a single space. The last line may have less than 10 elements, but at least 1 element. There should be no blank lines in the output.

Sample Input

样例

3
1 9
1 2 3 4 5 6 7 8 9
2 9
9 8 7 6 5 4 3 2 1
3 23
23 41 13 22 -3 24 -31 -11 -8 -7
3 5 103 211 -311 -45 -67 -73 -81 -99
-33 24 56


Sample Output
1 5
1 2 3 4 5
2 5
9 8 7 6 5
3 12
23 23 22 22 13 3 5 5 3 -3
-7 -3


题意

很有意思的题目, 给一组数字 不断的动态求给的数组中位数

我们可以维护两个堆一个大顶堆 一个小顶堆 不断交换他们堆顶的值

AC代码

#include <map>
#include <set>
#include <queue>
#include <stack>
#include <cmath>
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

#define ls st<<1
#define rs st<<1|1
#define LL long long
#define CLR(a,b) memset(a,(b),sizeof(a))

const int MAXN = 1e3+11;
const int mod = 1e9+7;
const int INF = 0x3f3f3f3f;

priority_queue<int,vector<int>, greater<int> > que_1; //小顶堆
priority_queue<int> que_2;
void init() {
while(!que_1.empty())
que_1.pop();
while(!que_2.empty())
que_2.pop();
}

int main() {
int T;
cin >> T;
while(T--) {
init();
int kk, n, x;
cin >> kk >> n;
cout << kk << ' ' << (n+1)/2 << endl;
for(int i = 1; i <= n; i++) {
cin >> x;
que_1.push(x);
que_2.push(x);
if(i%2==0)
continue;
while(que_1.top() != que_2.top()) {
int a = que_1.top();
int b = que_2.top();
que_1.pop(), que_2.pop();
que_1.push(b);
que_2.push(a);
}
cout << que_2.top() << ' ';
if(((i+1)/2)%10 == 0)
cout << "\n";
else if((n%2==1&&i==n) || (n%2==0&&i==n-1))
cout << "\n";
}

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: