題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=3282點擊打開鏈接
Running Median
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 1199 Accepted Submission(s): 431
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.
每到奇數時求中位數
用大根堆和小根堆儲存
維護小根堆數量奇數時爲大根堆+1偶數時相同
每次遇到奇數查詢小根堆頂元素即可
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
priority_queue<int > qmax;
priority_queue<int ,vector<int > ,greater <int > >qmin;
int cnt;
int n;
scanf("%d%d",&cnt,&n);
printf("%d %d\n",cnt,(n/2+1));
for(int i=1;i<=n;i++)
{
int mid;
scanf("%d",&mid);
if(qmin.size()==0)
qmin.push(mid);
else
{
if(mid>=qmin.top())
qmin.push(mid);
else
qmax.push(mid);
}
while(qmin.size()!=qmax.size()+1&&qmin.size()!=qmax.size())
{
if(qmin.size()>qmax.size())
{
int mid=qmin.top();
qmin.pop();
qmax.push(mid);
}
else
{
int mid=qmax.top();
qmax.pop();
qmin.push(mid);
}
}
if(i&1)
cout << qmin.top();
if((i+1)%20==0||i==n)
cout << endl;
else if(i&1)
cout << " ";
}
}
}