#include<iostream>
#include<cstdio>
using namespace std;
#define MAXN 100010
#define INF 99999999
bool f;
struct Node {
int key, sz, cnt;
Node *ch[2], *fa;
Node(){}
Node(int x, int y, int z) {
key = x, sz = y, cnt = z;
}
void updata() {
sz = ch[0]->sz + ch[1]->sz + cnt;
}
int cmp(int v) const {
if(v == key) return -1;
return v < key ? 0 : 1;
}
}nil(0, 0, 0);
Node *NIL = &nil;
struct Splay_Tree
{
Node *root;
int ncnt;
Node tree[MAXN+10];
void init() { root = NIL; ncnt = 0; }
Node *NewNode(){
Node &t = tree[++ncnt];
t.ch[0] = t.ch[1] = t.fa = NIL;
t.sz = t.cnt = 1;
return &tree[ncnt];
}
void Rotate(Node *x, int d)
{
Node *y = x->fa;
y->ch[!d] = x->ch[d];
if(x->ch[d] != NIL) x->ch[d]->fa = y;
x->fa = y->fa;
if(y->fa != NIL) y->fa->ch[y->fa->ch[1] == y] = x;
x->ch[d] = y;
y->fa = x;
if(y == root) root = x;
y->updata();
}
void splay(Node *x, Node *target)
{
Node *y, *z;
while(x->fa != target)
{
y = x->fa;
z = y->fa;
if(z == target)
{
if(x == y->ch[0]) Rotate(x, 1);
else Rotate(x, 0);
}
else
{
if(y == z->ch[0])
if(x == y->ch[0])
Rotate(y, 1), Rotate(x, 1);
else
Rotate(x, 0), Rotate(x, 1);
else
if(x == y->ch[0])
Rotate(x, 1), Rotate(x, 0);
else
Rotate(y, 0), Rotate(x, 0);
}
x->updata();
}
}
void insert(Node * &target, int val, Node *F)
{
if(target == NIL) {
target = NewNode();
target->key = val;
target->fa = F;
splay(target, NIL);
return ;
}
int d = target->cmp(val);
if(d == -1) {
target->cnt++;
target->sz++;
splay(target, NIL);
f = true;
return;
}
target->sz++;
insert(target->ch[d], val, target);
}
};
Splay_Tree sp;
int Left()
{
if(sp.root->ch[0] == NIL) return -1;
Node *p = sp.root->ch[0];
while(p->ch[1] != NIL)
p = p->ch[1];
return p->key;
}
int Right()
{
if(sp.root->ch[1] == NIL) return -1;
Node *p = sp.root->ch[1];
while(p->ch[0] != NIL)
p = p->ch[0];
return p->key;
}
int abs(int x)
{
return x > 0 ? x : -x;
}
int main()
{
int n;
sp.init();
scanf("%d", &n);
int ans = 0;
for(int i = 1; i <= n; i++)
{
int x;
scanf("%d", &x);
f = false;
sp.insert(sp.root, x, NIL);
if(i == 1) { ans += x; continue; }
else {
int t1 = Left();
int t2 = Right();
int t = INF;
if(t1 != -1) t = abs(x - t1);
if(t2 != -1) t = min(abs(x-t2), t);
if(f) t = 0;
ans += t;
}
}
printf("%d", ans);
}
由于bzoj说数据有问题 用自己的数据测的
[BZOJ 1588]营业额统计 && splay部分模版
最新推荐文章于 2018-06-30 21:22:38 发布