LUOGUP1801 黑匣子_NOI导刊2010提高(06)

来源:互联网 发布:c语言数据类型 编辑:程序博客网 时间:2024/04/19 22:00

一道堆排。主要思路就是建两个堆,一个大根堆,一个小根堆,大根堆存1-i的,小根堆存i+1-u[i]的。然后如果大根堆的堆顶小于了小根堆的堆顶说明大根堆不是1-i的了,就需要维护这两个堆,交换他们的堆顶。

#include<iostream>#include<cstdio>#include<algorithm>#include<cstring>using namespace std;int m,n;int t;//int i,j;int u[200005],a[200005],me[200005];int hp[200006];int cnt;void pusx(int x) {    hp[++cnt]=x;    int now=cnt;    while(now>1) {        int tp=now/2;        if(hp[tp]<hp[now]) {            swap(hp[tp],hp[now]);            now=tp;        } else break;    }}void pus(int x) {    a[++t]=x;    int now=t;    while(now>1) {        int tp=now/2;        if(a[tp]>a[now]) {            swap(a[tp],a[now]);            now=tp;        } else break;    }}int del() {    int res=a[1];    a[1]=a[t];    int now=1;    t--;    while(2*now<=t) {        int tp=now*2;        if(tp<t&&a[tp]>a[tp+1])tp++;        if(a[tp]<a[now]) {            swap(a[tp],a[now]);            now=tp;        } else break;    }    return res;}int delx() {    int res=hp[1];    hp[1]=hp[cnt];    int now=1;    cnt--;    while(2*now<=cnt) {        int tp=now*2;        if(tp<cnt&&hp[tp]<hp[tp+1])tp++;        if(hp[tp]>hp[now]) {            swap(hp[tp],hp[now]);            now=tp;        } else break;    }    return res;}int main() {    memset(a,0x7f,sizeof a);    memset(hp,0x8f,sizeof hp);    scanf("%d%d",&m,&n);    for(register int i=1; i<=m; i++) {        scanf("%d",&me[i]);    }    for(register int i=1; i<=n; i++) {        scanf("%d",&u[i]);    }    for(register int i=1; i<=n; i++) {        for(register int j=u[i-1]+1; j<=u[i]; j++) {            pus(me[j]);//建小根堆        }        int k;        int r;        r=del();        pusx(r);//建大根堆        while(a[1] < hp[1] && t>0 && cnt>0) {//我认为的核心内容,维护这两个堆            k=delx();            r=del();            pus(k);            pusx(r);        }        printf("%d\n",hp[1]);    }}
原创粉丝点击