POJ3784:Running Median

浅谈堆:https://www.cnblogs.com/AKMer/p/10284629.html

题目传送门:http://poj.org/problem?id=3784

用一个“对顶堆”动态维护中位数。

一个大根堆维护前半部分的权值,一个小根堆维护后半部分的权值。

新进来一个数如果小于大根对的权值就加进大根对,否则就加进小根堆。

每次动态维护大小,使得大根堆的大小为数字的一半。

大根对的堆顶就是中位数。

为了方便我把大根堆里的数取了个反也就变小根堆了。

时间复杂度:\(O(Tnlogn)\)

空间复杂度:\(O(n)\)

代码如下:

#include <cstdio>
#include <algorithm>
using namespace std;

const int maxn=1e4;

int ans[maxn];
int data,n,cnt;

int read() {
    int x=0,f=1;char ch=getchar();
    for(;ch<'0'||ch>'9';ch=getchar())if(ch=='-')f=-1;
    for(;ch>='0'&&ch<='9';ch=getchar())x=x*10+ch-'0';
    return x*f;
}

struct Heap {
    int tot;
    int tree[maxn];

    void ins(int v) {
        tree[++tot]=v;
        int pos=tot;
        while(pos>1) {
            if(tree[pos]<tree[pos>>1])
                swap(tree[pos],tree[pos>>1]),pos>>=1;
            else break;
        }
    }

    int pop() {
        int res=tree[1];
        tree[1]=tree[tot--];
        int pos=1,son=2;
        while(son<=tot) {
            if(son<tot&&tree[son|1]<tree[son])son|=1;
            if(tree[son]<tree[pos])
                swap(tree[son],tree[pos]),pos=son,son=pos<<1;
            else break;
        }
        return res;
    }
}T1,T2;

int main() {
    int T=read();
    while(T--) {
        data=read(),n=read();
        T1.tot=T2.tot=cnt=0;
        for(int i=1;i<=n;i++) {
            int x=read();
            if(x<=(-T1.tree[1]))T1.ins(-x);
            else T2.ins(x);
            while(T2.tot<i/2) {
                int res=T1.pop();
                T2.ins(-res);
            }
            while(T2.tot>i/2) {
                int res=T2.pop();
                T1.ins(-res);
            }
            if(i&1)ans[++cnt]=-T1.tree[1];
        }
        printf("%d %d\n",data,cnt);
        for(int i=1;i<=cnt;i++)
            if(i%10)printf("%d ",ans[i]);
            else printf("%d\n",ans[i]);
        if(cnt%10)puts("");
    }
    return 0;
}

转载于:https://www.cnblogs.com/AKMer/p/10286114.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值