[题解]Running Median

博客主要介绍了如何解决输入序列中奇数位置元素出现时计算中位数的问题,探讨了暴力排序、堆、链表以及平衡树(以Splay为例)等方法。重点在于利用平衡树在O(nlogn)的时间复杂度内完成查询和插入操作,以实现序列中每个阶段的中位数。
摘要由CSDN通过智能技术生成

题目描述
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.
样例输入 Copy
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
样例输出 Copy
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
提示
来源:Greater New York Regional 2009

问题传送门

题目的理解

这道题与洛谷P1168类似但输出有点***,对于题目描述,可知这道题让我们做一个维护区间序列 a a a的中位数,注意需要排序(对于有限的数集,可以通过把所有观察值高低排序后找出正中间的一个作为中位数。如果观察值有偶数个,通常取最中间的两个数值的平均数作为中位数。 --选自百度百科).

分析这道题

首先,注意序列个数达到奇数个时,要输出询问答案。

对于最暴力的方法

对于每次询问,做一遍查询,排序,输出 a n s k / 2 + 1 ans_{k / 2 + 1} ansk/2+1这个数即可。

分析时间复杂度为 O ( n 2 log ⁡ n ) O(n^2 \log n) O(n2logn),此时过不了这道题,但可以拿到 40 % 40 \% 40%的好成绩.

代码如下
#include<bits/stdc++.h>
using namespace std;
int n,a[100001];
int main(){
   
	scanf("%d",&n);
	for(int i=1;i<=n;i++){
   
		cin>>a[i];
		if(i==1)printf("%d\n",a[i]);
		if(i!=1&&i&1){
   
			sort(a+1,a+i+1);
			printf("%d\n",a[(1+i)/2]);
		}
	}return 0;
}
对于正解的方法1

用堆来维护,然后二分, 分析时间复杂度为 O ( n log ⁡ n ) . O(n \log n). O(nlogn).可以过,但这不是重点。

对此代码
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
priority_queue<int> big;
priority_queue<int, vector<int>, greater<int> > small;
int mai
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值