Splay树模版

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
using namespace std;
typedef long long LL;
const int maxn = 1000010;
int pre[maxn], ch[maxn][2], sz[maxn];
int root, top1;
 
int val[maxn];
 
 
void rotate(int x, int d)
{
    int y = pre[x];
    ch[y][d^1] = ch[x][d];
    pre[ch[x][d]] = y;
    if(pre[y])
        ch[pre[y]][ch[pre[y]][1] == y] = x;
    pre[x] = pre[y];
    ch[x][d] = y;
    pre[y] = x;
     
}
 
void Splay(int x, int goal)
{
    while(pre[x] != goal)
    {
        if(pre[pre[x]] == goal)
        {
            rotate(x, ch[pre[x]][0] == x);
        }
        else
        {
            int y = pre[x], z = pre[y];
            int d = (ch[z][0] == y);
            if(ch[y][d] == x)
            {
                rotate(x, d^1);
                rotate(x, d);
            }
            else
            {
                rotate(y, d);
                rotate(x, d);
            }
        }
    }
    if(goal == 0)
        root = x;
}
 
void NewNode(int &x, int f, int c)
{
     
    x = ++top1;
    ch[x][0] = ch[x][1];
    //sz[x] = 1;
    pre[x] = f;
     
    val[x] = c;
    //add[x] = 0;
}
 
void insert(int k)
{
    int x = root;
    if(x == 0)
    {
        NewNode(root, 0, k);
        return;
    }
    while(ch[x][k>val[x]])
        x = ch[x][k>val[x]];
    NewNode(ch[x][k>val[x]], x, k);
    Splay(ch[x][k>val[x]], 0);
}
int find1(int x)
{
    while(ch[x][0])
        x = ch[x][0];
    return x;
}
 
int find2(int x)
{
    while(ch[x][1])
        x = ch[x][1];
    return x;
}
 
int main()
{
    int n;
    scanf("%d", &n);
    int ans = 0;
    for(int i = 1; i <= n; i++)
    {
        int x;
        if(scanf("%d", &x) == EOF)
            x = 0;  
        insert(x); 
        if(i == 1)
        {
            ans += x;
        }
        else
        {
            int temp = 0x3f3f3f3f;
            if(ch[root][0])
                temp = min(x-val[find2(ch[root][0])], temp);
            if(ch[root][1])
                temp = min(val[find1(ch[root][1])]-x, temp);
            ans += temp;
        }       
    }
    printf("%d\n", ans);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值