您的位置:首页 > 运维架构

hdu 5349 维护序列 OR Treap

2015-08-04 18:47 579 查看
由于只删除最小值和只查询最大值,所以我们只要维护一个maxn和一个size即可,需要注意的是删除到集合空时需要重新将maxn赋值为无穷小。

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;

int main ()
{
int n;
while ( scanf("%d", &n) != EOF )
{
int op, tmp, maxn = -1111111111, size = 0;
for ( int i = 0; i < n; i++ )
{
scanf("%d", &op);
if ( op == 1 )
{
scanf("%d", &tmp);
size++;
if ( tmp > maxn ) maxn = tmp;
}
else if ( op == 2 )
{
if ( size > 0 )
{
size--;
if ( size == 0 ) maxn = -1111111111;
}
}
else
{
if ( size == 0 )
{
printf("0\n");
}
else
{
printf("%d\n", maxn);
}
}
}
}
return 0;
}


另外,别的平衡的数据结构也可以过,这里用的是Treap(主要是测模板),比赛推荐用multiset。

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
using namespace std;

struct Node
{
Node * ch[2];
int v, r, size;
int cmp( int x )
{
if ( x == v ) return -1;
return x < v ? 0 : 1;
}
void maintain()
{
size = 1;
if ( ch[0] != NULL ) size += ch[0]->size;
if ( ch[1] != NULL ) size += ch[1]->size;
}
};

Node * root;

void rotate( Node * & o, int d )
{
Node * k = o->ch[d ^ 1];
o->ch[d ^ 1] = k->ch[d];
k->ch[d] = o;
o->maintain();
k->maintain();
o = k;
}

void insert( Node * & o, int x )
{
if ( o == NULL )
{
o = new Node();
o->ch[0] = o->ch[1] = NULL;
o->v = x;
o->r = rand();
o->size = 1;
}
else
{
int d = ( x <= o->v ? 0 : 1 );
insert( o->ch[d], x );
if ( o->ch[d]->r > o->r )
{
rotate( o, d ^ 1 );
}
else
{
o->maintain();
}
}
}

void remove( Node * & o, int x )
{
int d = o->cmp(x);
if ( d == -1 )
{
if ( o->ch[0] != NULL && o->ch[1] != NULL )
{
int dd = ( o->ch[0]->r > o->ch[1]->r ? 1 : 0 );
rotate( o, dd );
remove( o->ch[dd], x );
}
else
{
Node * u = o;
if ( o->ch[0] == NULL ) o = o->ch[1];
else o = o->ch[0];
delete u;
}
}
else
{
remove( o->ch[d], x );
}
if ( o != NULL ) o->maintain();
}

int findm( Node * o, int d )
{
while ( o->ch[d] != NULL ) o = o->ch[d];
return o->v;
}

int main ()
{
int n;
while ( scanf("%d", &n) != EOF )
{
root = NULL;
for ( int i = 0; i < n; i++ )
{
int op, x;
scanf("%d", &op);
if ( op == 1 )
{
scanf("%d", &x);
insert( root, x );
}
else if ( op == 2 )
{
if ( root != NULL )
{
x = findm( root, 0 );
remove( root, x );
}
}
else
{
if ( root == NULL )
{
x = 0;
}
else
{
x = findm( root, 1 );
}
printf("%d\n", x);
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: