106. 动态中位数

题目链接

106. 动态中位数

动态维护中位数问题:依次读入一个整数序列, 每当已经读入的整数个数为奇数 时, 输出已读入的整数构成的序列的中位数。

解题思路

对顶堆

维护两个堆:大根堆:维护前 \(n/2\) 小数,小根堆:维护后 \(n-n/2\) 大数,遇到奇数个数时,小根堆堆顶即为所求

  • 时间复杂度:\(O(nlogn)\)

代码

// Problem: 动态中位数
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/108/
// Memory Limit: 256 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

// %%%Skyqwq
#include <bits/stdc++.h>
 
//#define int long long
#define help {cin.tie(NULL); cout.tie(NULL);}
#define pb push_back
#define fi first
#define se second
#define mkp make_pair
using namespace std;
 
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
 
template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; }
template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; }
 
template <typename T> void inline read(T &x) {
    int f = 1; x = 0; char s = getchar();
    while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
    while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar();
    x *= f;
}

priority_queue<int> q1;
priority_queue<int,vector<int>,greater<int>> q2;
int t,n;
int main()
{
    scanf("%d",&t);
    for(int i=1;i<=t;i++)
    {
    	scanf("%*d%d",&n);
    	printf("%d %d\n",i,(n+1)/2);
    	while(q1.size())q1.pop();
    	while(q2.size())q2.pop();
    	int cnt=0;
    	for(int j=1;j<=n;j++)
    	{
    		int x;
    		scanf("%d",&x);
    		if(q2.size()==0)
    			q2.push(x);
    		else if(q1.size()<q2.size())
    		{
    			if(x>q2.top())
    			{
    				int t=q2.top();
    				q2.pop();
    				q1.push(t);
    				q2.push(x);
    			}
    			else
    				q1.push(x);
    		}
    		else
    		{
    			if(x<q1.top())
    			{
    				int t=q1.top();
    				q1.pop();
    				q2.push(t);
    				q1.push(x);
    			}
    			else
    				q2.push(x);
    		}
    		if(j&1)
    		{
    			printf("%d ",q2.top());
    			cnt++;
    			if(cnt%10==0)puts("");
    		}
    	}
    	if(cnt%10!=0)puts("");
    }
    return 0;
}
posted @ 2022-04-03 10:11  zyy2001  阅读(75)  评论(0编辑  收藏  举报