1002 Running Median

锦林不睡觉發表於2024-06-21

思路:維護一個對頂堆

題目連結:https://ac.nowcoder.com/acm/contest/22904/1002

程式碼部分

#include"bits/stdc++.h"
using namespace std;
int fr(){
    char ch;
    int sum,sign=1;
    while((ch=getchar())>'9'||ch<'0')
        if(ch=='-')
            sign=-1;
    sum=ch-'0';
    while((ch=getchar())>='0'&&ch<='9')
        sum=(sum<<3)+(sum<<1)+ch-'0';
    return sum*sign;
}
int main(){
    int p;
    p=fr();
    for(int i=1;i<=p;i++){
        int x,y;
        x=fr(),y=fr();
        printf("%d %d\n",x,y+1>>1);
        priority_queue<int,vector<int>,greater<int>>head1;
        priority_queue<int,vector<int>,less<int>>head2;
        int k;
        k=fr();
        printf("%d ",k);
        head1.push(k);
        for(int i=2;i<=y;i++){
            k=fr();
            if(head1.top()<k)head1.push(k);
            else head2.push(k);
            if(head1.size()>head2.size()+1){
                head2.push(head1.top());
                head1.pop();
            }
            else if(head2.size()>head1.size()+1){
                head1.push(head2.top());
                head2.pop();
            }
            if(i%2==1){
                if(head1.size()<head2.size())printf("%d ",head2.top());
                else printf("%d ",head1.top());
            }
            if(i%20==0)printf("\n");
        }
        printf("\n");
    }
}

相關文章