Running Median
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 6601 Accepted: 2871
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
题目大意:
输入的第一行包含一个整数 P,(1 ≤ P ≤ 1000),它是后面的数据集的数量。 每个数据集的第一行包含数据集编号,后跟一个空格,后跟一个奇数十进制整数 M,(1 ≤ M ≤ 9999),给出要处理的有符号整数的总数。 数据集中剩余的行由值组成,每行 10 个,由一个空格分隔。 数据集中的最后一行可能包含少于 10 个值。
实现思路:
1.大根堆
大根堆就是根节点是整棵树的最大值(根节点大于等于左右子树的最大值),对于他的任意子树,根节点也是最大值。大根堆有两个操作,一个创建堆heapInsert时间复杂度是O(N),还有一个操作是当大根堆里的某个节点的值,发生变化的时候,需要对这个大根堆进行调整
2.小根堆
和大根堆刚好相反,根节点是整棵树的最小值
小根堆的根节点作为中位数,输入的数据若是大于小根堆的根节点则存入小根堆,若是小于小根堆的根节点则存入大根堆。若大根堆的数据量大于小根堆则将数据存入小根堆直至二者二者相等,因为小根堆的堆顶存储中位数故小根堆的数据量可以比大根堆的多一个,这样便实现了中文数的存储。
poj提交结果:
代码结果:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
using namespace std;
priority_queue <int, vector<int>, greater<int> > q1;//是小根堆
priority_queue <int> q2; //大根堆
vector <int > a;
void Add(int x) //往大根堆 小根堆添加数据的操作
{
if (q1.empty())
{ //若小根堆为空则直接添加到小根堆里
q1.push(x);
return;
}
if (x > q1.top()) //若即将添加的数据比小根堆的根节点大则添加进小根堆相反则添加进大根堆
q1.push(x);
else
q2.push(x);
while (q2.size() > q1.size())
{//大根堆数据比小根堆数据多则将大根堆的根节点数据添加进小根堆
q1.push(q2.top());
q2.pop();
}
while (q1.size() > q2.size() + 1)
{//小根堆的堆顶存储中位数故小根堆的数据量可以比大根堆的多一个
q2.push(q1.top());
q1.pop();
}
}
int main()
{
int t, k; //t代表数据集
cin >> t;
while (t--)
{
while (q1.size()) q1.pop();
while (q2.size()) q2.pop();
a.clear();
int m, n; // 第m号数据集有n个数据
cin >> m >> n;
for (int i = 1; i <= n; i++)
{
cin >> k;
Add(k);
if (i % 2 != 0) a.push_back(q1.top());
}
cout << m << " " << (n + 1) / 2 << endl;
for (int i = 0; i < a.size(); i++)
{
if (i > 0 && i % 10 == 0) putchar('\n');
if (i % 10) putchar(' ');
printf("%d", a[i]);
}
cout << endl;
}
return 0;
}