[洛谷P2073] 送花
来源:互联网 发布:高分一号数据操作教程 编辑:程序博客网 时间:2024/06/05 00:44
可以作为入门平衡树的第一道题。
1 试题大意
维护一个序列,支持以下操作:
- 插入一个新的元素,包括它的Key和Value
- 删除Key最小的元素
- 删除Key最大的元素
并在结束时分别输出序列中元素的Key总和与Value总和。
2 分析
平衡树这里用Splay实现。对于删除操作,由于在两端,实现起来较为简单。
3 参考程序
#include <cstdio>#define lc(x) ((x)==(ch[fa[(x)]][0]))#define _rst {fa[0]=0;ch[0][0]=ch[0][1]=0;}using namespace std;int fa[100005],ch[100005][2],k[100005],v[100005],root=0,ind=0;long long travel1(int x){ if(!x)return 0; return travel1(ch[x][0])+travel1(ch[x][1])+k[x];}long long travel2(int x){ if(!x)return 0; return travel2(ch[x][0])+travel2(ch[x][1])+v[x];}inline void rotate(int p){ int q=fa[p],y=fa[q],x=ch[q][1]==p; ch[q][x]=ch[p][x^1]; _rst; fa[ch[q][x]]=q; _rst; ch[p][x^1]=q; _rst; fa[q]=p; _rst; fa[p]=y; _rst; if(y) if(ch[y][0]==q)ch[y][0]=p; else if(ch[y][1]==q)ch[y][1]=p;}inline void splay(int x){ for(int y;y=fa[x];rotate(x)) if(fa[y])rotate((x==lc(y))==(y==lc(fa[y]))?y:x); root=x;}inline void insert(int x,int key,int value){ int y; while(1){ y=ch[x][k[x]<key]; if(k[y]==key||k[x]==key)return; if(y==0){ y=++ind; k[y]=key; v[y]=value; ch[y][0]=ch[y][1]=0; fa[y]=x; ch[x][k[x]<key]=y; break; } x=y; } splay(y);}inline void insert(int key,int value){ if(root)insert(root,key,value); else{ root=++ind; k[root]=key; v[root]=value; ch[root][0]=ch[root][1]=0; fa[root]=0; }}inline void delmin(int x){ int t=x,l=0; if(!t)return; while(ch[t][0])l=t,t=ch[t][0]; if(fa[t]==0){ root=ch[t][1]; fa[ch[t][1]]=0; ch[t][0]=ch[t][1]=fa[t]=0; return; } ch[l][0]=ch[t][1]; if(ch[t][1])fa[ch[t][1]]=l; ch[t][0]=ch[t][1]=fa[t]=0;}inline void delmax(int x){ int t=x,l=0; if(!t)return; while(ch[t][1])l=t,t=ch[t][1]; if(fa[t]==0){ root=ch[t][0]; fa[ch[t][0]]=0; ch[t][0]=ch[t][1]=fa[t]=0; return; } ch[l][1]=ch[t][0]; if(ch[t][0])fa[ch[t][0]]=l; ch[t][0]=ch[t][1]=fa[t]=0;}int main(){ int t1,t2,t3; long long s1,s2; for(;;){ scanf("%d",&t1); switch(t1){ case 1: scanf("%d%d",&t2,&t3); insert(t3,t2); break; case 2: delmax(root); break; case 3: delmin(root); break; case -1: printf("%lld %lld\n",travel2(root),travel1(root)); return 0; } }}
阅读全文
0 0
- [洛谷P2073] 送花
- 洛谷P2073 送花_Treap
- 【BZOJ】【P2073】【POI2004】【PRZ】【题解】【状压DP+枚举子集】
- 送花
- 送花-ACM算法题
- 南邮 OJ 2084 送花
- 送花 南邮NOJ网络选拔赛2084
- NOJ 网络赛 L题 送花
- 洛谷
- 洛谷
- 洛谷
- iOS Delegate学习(送花ABC,一个悲伤的故事)
- 平衡树(STL)——Luogu2073 送花
- 洛谷 中位数
- 洛谷p1373
- 洛谷 P1579
- 洛谷P1313
- 洛谷1028
- [第五季]8.CSS概述及选择器和优先级
- eWebEditor商业编辑器序列号破解
- ZwQuerySystemInformation
- arm linux中一些重要的宏及地址定义
- Go语言实现的素数筛选程序
- [洛谷P2073] 送花
- 2017 Multi-University Training Contest
- MySQL修改视图
- 从键盘接收一个文件夹路径,删除该文件夹
- docker run hello-world
- 博主已经沉迷高考(shadowverse)不能自拔
- AGC018:Tree and Hamilton Path(dfs & 树 哈密尔顿回路)
- 51nod 1127 最短的包含字符串(尺取法)
- apache-comnons系列之commons-email1.4 学习笔记