POJ3784 Running Median

动态维护中位数 对顶堆

#include<cstdio>
#include<queue>
using namespace std;
const int maxn = 1e4;
int a[maxn];
priority_queue<int,vector<int>,greater<int> > smallheap;
priority_queue<int,vector<int>,less<int> > bigheap;
int main()
{
    int t; scanf("%d",&t);
    int op, n, x;
    while(t--){
        scanf("%d%d",&op,&n);
        while(!bigheap.empty()) bigheap.pop();
        while(!smallheap.empty()) smallheap.pop();
        for(int i = 1; i <= n; i++){
            scanf("%d",&x);
            if(bigheap.empty() || bigheap.top() > x) bigheap.push(x);
            else smallheap.push(x);
            while(bigheap.size() > (i+1)/2){
                int tmp = bigheap.top();
                bigheap.pop();
                smallheap.push(tmp);
            }
            while(bigheap.size() < (i+1)/2){
                int tmp = smallheap.top();
                smallheap.pop();
                bigheap.push(tmp);
            }
            if((i+1)%2 == 0) a[(i+1)/2] = bigheap.top();
        }
        printf("%d %d\n",op,(n+1)/2);
        int cnt = 0;
        for(int i = 1; i <= (n+1)/2; i++){
            printf("%d ",a[i]);
            cnt++;
            if(cnt % 10 == 0) printf("\n");
        }
        if(cnt % 10 != 0) printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/kkjy_00/article/details/87003840
今日推荐