[hdu-4006]The kth great number 题解

来源:互联网 发布:如何删除筛选后的数据 编辑:程序博客网 时间:2024/05/18 09:19

题目传送门
题意解析:题目就是有n次操作,每次操作可以加入一个数或者查询,查询是查找在队伍里的第k大的数(k是一开始就给你的,每个测试数据k都是固定的)。


My opinion:这题目一开始拿到时,看到n<=1000000和有多组测试数据着实吓了我一跳,我都怕输入超时了。感觉可以维护一个优先队列,但是又觉得十分麻烦,于是决定弄一个很暴力的方法。可以使用堆,每次维护一个只存在k个数的小根堆,每次加入一个数的话,如果堆中没到达k个数就直接加。如果到达了k个数的话,那么就要分类了,如果当前的数比堆顶小(或者等于)的话,因为已经是k个数的堆了,那么堆顶一定是第k大的数,而且没有删除操作,直接无视之;如果比当前大的话,就删除根,加入当前数。每次查询的话,就输出堆顶。
总结:
1、输入。
2、每次按分类操作就好了。
(又是个写不出总结的题)


一个神奇的代码:

#include<iostream>#include<cmath>#include<cstdio>#include<cstring>#include<algorithm>#include<queue>#define rep(i,a,n) for (int i=a;i<=n;i++)#define per(i,a,n) for (int i=a;i>=n;i--)#define Clear(a,x) memset(a,x,sizeof(a))#define ll long long#define INF 2000000000#define eps 1e-8using namespace std;ll read(){    ll x=0,f=1;    char ch=getchar();    while (ch<'0'||ch>'9') f=ch=='-'?-1:f,ch=getchar();    while (ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();    return x*f;}const int maxn=1000005;struct node{    int key,l,r,dis;}a[maxn];int n,k,len,top,now;char ch[5];int merge(int A,int B){    if (A==0) return B;    if (B==0) return A;    if (a[A].key>a[B].key)        swap(A,B);    a[A].r=merge(a[A].r,B);    if (a[a[A].r].dis>a[a[A].l].dis)        swap(a[A].l,a[A].r);    a[A].dis=a[a[A].r].dis+1;    return A;}int main(){    while (~scanf("%d%d",&n,&k)){        //Clear(a,0);        top=0,len=0,now=0;        rep(i,1,n){            scanf("%s",ch);            if (ch[0]=='I'){                int x=read();                a[++len].key=x;                a[len].l=a[len].r=0;                a[len].dis=0;                if (top<k){                    if (now==0) now=len;                        else now=merge(now,len);                    top++;                }else{                    if (x<=a[now].key) continue;                        else{                            int l=a[now].l,r=a[now].r;                            a[now].l=0,a[now].r=0;                            now=merge(l,r);                            now=merge(now,len);                        }                }            }else{                printf("%d\n",a[now].key);            }        }    }    return 0;}

不附上AC记录了(我才不会告诉你是我懒呢)
不要问我为什么写的是左偏树,因为我们这边的大佬把这题放进了左偏树的模板题里面了。其实用普通的小根堆也可以写。

原创粉丝点击