bzoj1588 [HNOI2002]营业额统计 (Splay)

来源:互联网 发布:淘宝首页装修图片 编辑:程序博客网 时间:2024/05/17 23:29

题意:中文题。。不多说。

这题就是裸的Splay模板。。。但是出了一个问题。。导致我WA了12次(最后随机数对拍才找到)。。。

没插入一个点,把这个点旋转到根,然后找到根的左子树最靠右边的的,根的右子树最靠左边的点,然后相减处理下就好。。。

这里我是WA在,每把一个点旋转到根,忘记把表示根节点的那个点修改成根了。。。然后还RE了几发,原因是我写的是多组数据(测试是单组数据),然后我需要初始化,删除整个树的时候指针可能越界访问了。。

#include<cstdio>#include<cstring>#include<algorithm>#include<cmath>using namespace std;const int MAXN=500010;struct Node{Node *ch[2];Node *fa;int val;}p[MAXN];Node *null=&p[0];int tot;Node *root=null;void Rotate(Node *x,int c){Node *y=x->fa;y->ch[!c]=x->ch[c];if(x->ch[c]!=null)x->ch[c]->fa=y;x->fa=y->fa;if(y->fa!=null){if(y->fa->ch[0]==y)y->fa->ch[0]=x;elsey->fa->ch[1]=x;}y->fa=x;x->ch[c]=y;if(y==root)x=root;}void splay(Node *x,Node *f){while(x->fa!=f){if(x->fa->fa==f){if(x->fa->ch[0]==x)Rotate(x,1);elseRotate(x,0);}else{Node *y=x->fa,*z=y->fa;if(z->ch[0]==y){if(y->ch[0]==x)Rotate(y,1),Rotate(x,1);elseRotate(x,0),Rotate(x,1);}else{if(y->ch[1]==x)Rotate(y,0),Rotate(x,0);elseRotate(x,1),Rotate(x,0);}}}}Node *new_Node(int val){Node *rt=&p[++tot];rt->ch[0]=rt->ch[1]=rt->fa=null;rt->val=val;return rt;}Node *root1=null;Node *insert(Node *rt,int val){if(rt==null){rt=new_Node(val);root1=rt;return rt;}if(rt->val==val)return rt;if(rt->val>val){rt->ch[0]=insert(rt->ch[0],val);rt->ch[0]->fa=rt;}else{rt->ch[1]=insert(rt->ch[1],val);rt->ch[1]->fa=rt;}return rt;}Node *Delete(Node *&rt){if(rt==null)return null;if(rt->ch[0]!=null)rt->ch[0]=Delete(rt->ch[0]);if(rt->ch[1]!=null)rt->ch[1]=Delete(rt->ch[1]);rt=null;return rt;}int main(){int n,i;null->val=0;//freopen("out.txt","r",stdin);//freopen("out1.txt","w",stdout);while(scanf("%d",&n)==1){tot=0;int x;int ans=0;for(i=1;i<=n;i++){x=0;scanf("%d",&x);root1=null;root=insert(root,x);if(root1==null)continue;splay(root1,null);root=root1;//根节点要随着相应的改变if(i==1){ans+=x;continue;}Node *L,*R;L=root1->ch[0];while(L!=null&&L->ch[1]!=null)L=L->ch[1];R=root1->ch[1];while(R!=null&&R->ch[0]!=null)R=R->ch[0];int temp1=1<<30,temp2=1<<30;if(L!=null)temp1=x-(L->val);if(R!=null)temp2=(R->val)-x;int temp=min(temp1,temp2);ans+=temp;}printf("%d\n",ans);root=Delete(root1);}return 0;}


0 0
原创粉丝点击