Acwing_265营业额统计【平衡树Treap】

题目链接:Acwing_265营业额统计

思路很简单,平衡树的话可以自己手写一个或者利用set集合也可以做这个题目

#include <iostream>
#include <ctime>
#include <cstdio>
using namespace std;

typedef long long LL;
const int N = 34000, INF = 1e7;
int n, idx, root;
LL res;
struct Node{
    int l, r, key, val;
} tr[N];

int get_node(int key)
{
    tr[++ idx].key = key;
    tr[idx].val = rand();
    return idx;
}

void build()
{
    get_node(-INF), get_node(INF);
    root = 1, tr[root].r = 2;
}

void zig(int &p)
{
    int q = tr[p].l;
    tr[p].l = tr[q].r, tr[q].r = p, p = q;
}

void zag(int &p)
{
    int q = tr[p].r;
    tr[p].r = tr[q].l, tr[q].l = p, p = q;
}

void insert(int &p, int key)
{
    if ( !p ) p = get_node(key);
    else if ( tr[p].key == key ) return;
    else if ( tr[p].key > key ) 
    {
        insert(tr[p].l, key);
        if ( tr[tr[p].l].val > tr[p].val ) zig(p);
    }
    else
    {
        insert(tr[p].r, key);
        if ( tr[tr[p].r].val > tr[p].val ) zag(p);
    }
}

int get_prev(int p, int key)    //找小于等于key的最大数
{
    if ( !p ) return -INF;
    else if ( tr[p].key > key ) return get_prev(tr[p].l, key);
    return max(tr[p].key, get_prev(tr[p].r, key));
}

int get_next(int &p, int key)   //找大于等于key的最小数
{
    if ( !p ) return INF;
    else if ( tr[p].key < key ) return get_next(tr[p].r, key);
    return min(tr[p].key, get_next(tr[p].l, key));
}

int main()
{
    build();
    cin >> n;
    for ( int i = 0; i < n; i ++ ) 
    {
        int x;
        scanf("%d", &x);
        if ( !i ) res += x;
        else res += min(x - get_prev(root, x), get_next(root, x) - x);
        insert(root, x);
    }
    cout << res;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值