HNOI2002营业额统计 (伸展树---模板题)


 

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string.h>
#include <queue>                //HNOI2002 (伸展树---模板题)
#define N 100010
#define inf 1<<30
using namespace std;
int pre[N], key[N], ch[N][2], root, tot;   //分别表示父结点,键值,左右孩子(0为左孩子,1为右孩子),根结点,结点数量  
void newnode(int &r, int father, int k)  //创建新节点, 同时也修改r本身那个数
{
    r=++tot;
    pre[r]=father;
    ch[father][key[father]<k]=r;
    ch[r][0]=ch[r][1]=0;
    key[r]=k;
    return ;
}
void rotate(int x, int kind)  //kind旋转方向,0代表左旋,1代表右旋
{
    int k=pre[x], g;
    ch[k][!kind]=ch[x][kind];
    pre[ch[x][kind]]=k;
    ch[x][kind]=k;
    pre[x]=pre[k];
	g=pre[k];
    pre[k]=x;
    if(g==0)return ;
    else if(ch[g][0]==k)
        ch[g][0]=x;
    else ch[g][1]=x;
    return ;
}
void Splay(int x, int goal)            //伸展,将节点x, goal为目标序号
{
    int k, g, j;
    while(pre[x]!=goal)
    {
        k=pre[x];
        if(pre[k]==goal)
        {
            rotate(x, key[k]>key[x]);
        }
        else
        {
            g=(ch[k][0]==x?0:1); //判断x是k的左孩子还是右孩子
            j=(ch[pre[k]][0]==k?0:1);
            if(g==j)  //如果同向
            {
                rotate(k, !g);
                rotate(x, !g);
            }
            else 
            {
                rotate(x, key[k]>key[x]);
                k=pre[x];
                rotate(x, key[k]>key[x]);
            }
        }
    }
    if(goal==0)root=x;
    return ;
}
int insert(int num)
{
    int r=root, k, g;
    while(r)
    {
        k=r;
        if(key[r]==num)
        {
            Splay(r, 0);
            return 0;
        }
        if(key[r]>num)
            r=ch[r][0];
        else r=ch[r][1];
    }
    newnode(g, k, num);
    Splay(g, 0);
    return 1;
}
int getright(int x, int g)
{
    int k;
    if(!x)return inf;
    while(x)
    {
        k=key[x];
        x=ch[x][1];
    }
    return g-k;
}
int getleft(int x, int g)
{
    int k;
    if(!x)return inf;
    while(x)
    {
        k=key[x];
        x=ch[x][0];
    }
    return k-g;
}

int main()
{
    int n, t, ans, k, a, b;
    while(scanf("%d", &n)!=EOF)
    {
        root=tot=0;
        for(t=1; t<=n; ++t)
        {
            if(scanf("%d", &k)==EOF)k=0;    //要注意这里
            if(t==1)
			{
				ans=k;
				newnode(root, 0, k);
				continue;
			}
			if(!insert(k)) //如果之前树中已经有了k,则直接continue,同时将原树中那个k(Splay一下)
                continue;
            a=getright(ch[root][0], k);
            b=getleft(ch[root][1], k);
            ans+=min(a, b);
        }
        printf("%d\n", ans);
    }
    return 0;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值