Description
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.
Input
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.
Output
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
题解:
暴力在在UVALive 4555上可以过,但是poj会判t,所以采用优先队列来做。
用两个优先队列来模拟最大最小堆。中位数是x,就是有一半数比x小,一半数比x大。刚好符合堆的特点。用一个从大到小排序的优先队列q1来模拟小于x的数。从小到大排序的优先队列q2来模拟大于x的数。动态维护两个优先队列的元素个数。q1.size()=q2.size() 输入的数为偶数个时,q1.size()=q2.size()+1 输入的数为奇数个时。每次要输出的中位数恰好是q1.top().
代码如下:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
#include<cmath>
#include<map>
#include<stack>
#include<vector>
#include<queue>
#include<set>
#include<algorithm>
#define max(a,b) (a>b?a:b)
#define min(a,b) (a<b?a:b)
#define swap(a,b) (a=a+b,b=a-b,a=a-b)
#define maxn 320007
#define N 100000000
#define INF 0x3f3f3f3f
#define mod 1000000009
#define e 2.718281828459045
#define eps 1.0e18
#define PI acos(-1)
#define lowbit(x) (x&(-x))
#define read(x) scanf("%d",&x)
#define put(x) printf("%d\n",x)
#define memset(x,y) memset(x,y,sizeof(x))
#define Debug(x) cout<<x<<" "<<endl
#define lson i << 1,l,m
#define rson i << 1 | 1,m + 1,r
#define ll long long
//std::ios::sync_with_stdio(false);
//cin.tie(NULL);
using namespace std;
priority_queue<int>q1;
priority_queue<int,vector<int>,greater<int>>q2;
int main()
{
int t;
cin>>t;
while(t--)
{
while(q1.size())
q1.pop();
while(q2.size())
q2.pop();
int cnt,n;
cin>>cnt>>n;
cout<<cnt<<" "<<n/2+1<<endl;
for(int i=1;i<=n;i++)
{
int x;
cin>>x;
if(q1.empty())
q1.push(x);
else
{
if(x>q1.top())
q2.push(x);
else
q1.push(x);
}
while(q1.size()<q2.size())
{
q1.push(q2.top());
q2.pop();
}
while(q1.size()>q2.size()+1)
{
q2.push(q1.top());
q1.pop();
}
if(i%20==1)
cout<<q1.top();
else if(i%2)
cout<<" "<<q1.top();
if(!(i%20))
cout<<endl;
}
cout<<endl;
}
}