hdu 5349 维护序列 OR Treap
2015-08-04 18:47
579 查看
由于只删除最小值和只查询最大值,所以我们只要维护一个maxn和一个size即可,需要注意的是删除到集合空时需要重新将maxn赋值为无穷小。
另外,别的平衡的数据结构也可以过,这里用的是Treap(主要是测模板),比赛推荐用multiset。
#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; }
相关文章推荐
- 使用 jsch 连接linux
- shell知识点小结
- 微信公众号开发之被逼学web服务端1-----使用SecureCRT连接Linux服务器
- Linux下tomcat作为守护进程运行(开机启动、以指定的用户运行、解决非root身份不能绑定1024以下端口的问题)的配置方法
- CentOS 6.3下部署LVS(NAT)+keepalived实现高性能高可用负载均衡
- git Bash 安装&配置与基本操作
- git Bash 安装&配置与基本操作
- jq尺寸和位置总结篇(width scrollTop position offset)
- 设计模式之工厂模式
- linux bash shell之declare
- ceph存储 Linux-Futex浅析
- Linux 命令tail手动实现
- Linux ACL权限设置
- 实施,运维,开发驻场时与客户沟通需求的案例与技巧
- mac/linux常用命令
- CentOS_6.5安装Nginx+PHP+MySQL
- tomcat管理页面用户角色、用户名、用户密码的配置
- Linux服务器编程(1)
- Ubuntu配置Apache+PHP+MySQL
- 构建高并发高可用的电商平台架构实践