tyvj P1185 营业额统计

原题链接:http://www.tyvj.cn/p/1185
Treap的应用,具体如下:

#include
#include
#include
#define Max_N 40000
#define _min(a,b) ((a)>(b) ? (b) :(a))
#define _abs(x) ((x) < 0 ? (-(x)) : (x))
typedef struct _treap{
    int val, fix;
    struct _treap *ch[2];
}treap, *Treap;
treap stack[Max_N];
int sz = 0;
int _random(){
    static int x = 1840828537;
    x += (x << 2) | 1;
    return x;
}
void rotate(Treap *x, int c){
    Treap k = (*x)->ch[!c];
    (*x)->ch[!c] = k->ch[c];
    k->ch[c] = *x;
    *x = k;
}
void insert(Treap *x, int val, int fix){
    int d = 0;
    if (*x == NULL){
        *x = &stack[sz++];
        (*x)->ch[0] = (*x)->ch[1] = NULL;
        (*x)->val = val, (*x)->fix = fix;
    } else {
        d = val > (*x)->val;
        insert(&((*x)->ch[d]), val, fix);
        if ((*x)->ch[d]->fix < (*x)->fix) rotate(x, !d);
    }
}
int pre(Treap x, int val){
    int ret = -1;
    for (; x != NULL;){
        if (x->val <= val){
            ret = x->val;
            x = x->ch[1];
        } else {
            x = x->ch[0];
        }
    }
    return ret;
}
int suc(Treap x, int val){
    int ret = -1;
    for (; x != NULL;){
        if (x->val >= val){
            ret = x->val;
            x = x->ch[0];
        } else {
            x = x->ch[1];
        }
    }
    return ret;
}
int main(){
#ifdef LOCAL
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w+", stdout);
#endif
    Treap root = NULL;
    int i, n, t, v1, v2, ans = 0;
    scanf("%d", &n);
    for (i = 0; i < n; i++){
        scanf("%d", &t);
        if (i == 0){
            ans += t;
        } else {
            v1 = pre(root, t), v2 = suc(root, t);
            if (-1 == v1 || -1 == v2) ans += (-1 == v1 ? _abs(v2 - t) : abs(v1 - t));
            else ans += _min(_abs(v1 - t), _abs(v2 - t));
        }
        insert(&root, t, _random());
    }
    printf("%d\n", ans);
    return 0;
}

你可能感兴趣的:(Treap)