[HNOI2002]营业额统计 二叉搜索树的简单入门 splay
2014-11-04 22:41
253 查看
题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=1588
思路:搞的方法有很多,splay第一题,代码主要是仿照着别人的写得,通过本题对平衡二叉树的理解有所加深。
code;
思路:搞的方法有很多,splay第一题,代码主要是仿照着别人的写得,通过本题对平衡二叉树的理解有所加深。
code;
#include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int maxn=1000010; const int INF=0x3f3f3f3f; int pre[maxn],ch[maxn][2],key[maxn]; int root,tot1; //debug** void Treavel(int x) { if(x){ printf("node:%2d left:%2d right:%2d key:%2d\n",x,ch[x][0],ch[x][1],key[x]); Treavel(ch[x][0]); Treavel(ch[x][1]); } } void debug(int x) { printf("root:%2d\n",root); Treavel(root); } //debug** void NewNode(int &r,int fa,int k) { r=++tot1; pre[r]=fa; ch[r][0]=ch[r][1]=0; key[r]=k; } void init() { root=tot1=0; ch[root][0]=ch[root][1]=key[root]=pre[root]=0; } void Rotate(int x,int kind) { int y=pre[x]; ch[y][kind^1]=ch[x][kind]; pre[ch[x][kind]]=y; if(pre[y]) ch[pre[y]][ch[pre[y]][1]==y]=x; pre[x]=pre[y]; ch[x][kind]=y; pre[y]=x; } void Splay(int r,int goal) { while(pre[r]!=goal){ if(pre[pre[r]]==goal){ Rotate(r,ch[pre[r]][0]==r); } else{ int y=pre[r]; int kind=ch[pre[y]][0]==y; if(ch[y][kind]==r){ Rotate(r,kind^1); Rotate(r,kind); } else{ Rotate(y,kind); Rotate(r,kind); } } } if(goal==0) root=r; } //插入一个值为k的结点 void Insert(int k) { int r=root; if(r==0){ NewNode(root,0,k); return ; } while(ch[r][key[r]<k]) r=ch[r][key[r]<k]; NewNode(ch[r][key[r]<k],r,k); Splay(ch[r][key[r]<k],0); } int Get_Min(int r) { while(ch[r][0]) r=ch[r][0]; return r; } int Get_Max(int r) { while(ch[r][1]) r=ch[r][1]; return r; } int main() { int n; init(); scanf("%d",&n); int num,ans=0; for(int i=0;i<n;i++){ if(scanf("%d",&num)==EOF)num=0; //此处不加就wa,输入比较神奇吗? Insert(num); if(i==0) ans+=num; else{ int tmp=INF; if(ch[root][0]) tmp=min(tmp,key[root]-key[Get_Max(ch[root][0])]); if(ch[root][1]) tmp=min(tmp,key[Get_Min(ch[root][1])]-key[root]); ans+=tmp; } } printf("%d\n",ans); return 0; }
相关文章推荐
- 1588: [HNOI2002]营业额统计 splay 入门
- HNOI 2002 营业额统计(Splay入门)
- Splay入门题目 [HNOI2002]营业额统计
- Splay入门题+1588: [HNOI2002]营业额统计
- BZOJ1588 HNOI2002 营业额统计 [Splay入门题]
- hnoi 2002 营业额统计(splay入门题)
- 1588: [HNOI2002]营业额统计(Splay树入门)
- [HNOI2002]营业额统计(Splay tree 入门)
- HNOI_2002 营业额统计(Splay)
- bzoj 1588 [HNOI2002]营业额统计 splay
- BZOJ 1588: [HNOI2002]营业额统计 Splay版(模板题)
- [HNOI2002]营业额统计 Splay tree入门题
- [BZOJ1588]HNOI2002营业额统计|splay
- HNOI2002 营业额统计 splay
- [Bzoj1588][HNOI2002]营业额统计 (Treap|Splay)
- 【bzoj1588】[HNOI2002]营业额统计 Splay
- 两道Splay小结--bzoj1112: [POI2008]砖块Klo&bzoj1588: [HNOI2002]营业额统计
- HNOI2002 营业额统计(SBT模板题&splay解法)
- 【SPLAY】 [HNOI2002] 营业额统计 模板
- [HNOI2002]营业额统计splay重写