Day2 C - Running Median

Day2 C - 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.
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.

翻译

对于这个问题,您将编写一个以32位有符号整数序列读取的程序。读取每个奇数索引值后,输出到目前为止接收到的元素的中值(中间值)。

输入

输入的第一行包含一个整数P,(1≤ P≤ 1000),这是后面的数据集数。每个数据集的第一行包含数据集编号,后跟一个空格,后跟一个奇数十进制整数M(1)≤ M≤ 9999),给出要处理的有符号整数的总数。

数据集中的其余行由值组成,每行10个,用单个空格分隔。

数据集中的最后一行可能包含少于10个值。

输出

对于每个数据集,输出的第一行包含数据集编号、单个空格和输出的中位数(应为输入值数量的一半加一)。输出中位数将位于以下行上,每行10个,由一个空格分隔。最后一行可以有少于10个元素,但至少有1个元素。输出中不应有空行。

代码

代码:

#include<stdio.h>
#include<iostream>
#include<set>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
int main()
{
    
    
    int t;
    scanf("%d",&t);
    while(t--)
    {
    
    
        int x,n,a;
        scanf("%d%d",&x,&n);
        priority_queue<int> p1;
        priority_queue<int,vector<int>,greater<int>> p2;

        vector<int> ans;
        for(int i=1;i<=n;i++)
        {
    
    
            scanf("%d",&a);
            if(p1.empty())
                p1.push(a);
            else
            {
    
    
                if(a>p1.top())
                   p2.push(a);
                else
                   p1.push(a);
            }
            while(p1.size()<p2.size())
            {
    
    
                p1.push(p2.top());
                p2.pop();
            }
            while(p2.size()<p1.size()-1)
            {
    
    
                p2.push(p1.top());
                p1.pop();
            }
            if(i&1)
                ans.push_back(p1.top());
        }
       printf("%d %d\n",x,ans.size());
       for(int i=1;i<=ans.size();i++)
       {
    
    
        if(i%10!=1)
            printf(" ");
        printf("%d",ans[i-1]);
        if(i%10==0)
        printf("\n");
       }
       printf("\n");
    }
}

总结

对顶推解法,找出中位数

猜你喜欢

转载自blog.csdn.net/MarigoldLi/article/details/119414112
今日推荐