bzoj 1588营业额统计(HNOI 2002)

时间:2023-03-09 07:25:16
bzoj 1588营业额统计(HNOI 2002)

http://www.lydsy.com/JudgeOnline/problem.php?id=1588

splay  bottom-up的数组实现。

题意就是给你一组数,求每个数与在其前面且与其最相近的数的差值的绝对值。

考虑splay二叉搜索树的特性,每新插入一个节点,比它小且最靠近它的数在是左子树中的最大值,另一半同理。

代码借鉴自:http://blog.csdn.net/ACM_cxlove?viewmode=contents

 #include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 1e5 + ;
const int inf = 0x3f3f3f3f;
int pre[maxn], key[maxn], ch[maxn][], root, size;
int n; void new_node(int &r, int father, int k){
r = ++size;
pre[r] = father;
key[r]= k;
ch[r][] = ch[r][] = ;
} void rotate(int x, bool d){// d = 1, right rotate
int y = pre[x];
ch[y][!d] = ch[x][d];
pre[ch[x][d]] = y;
if(pre[y]) ch[pre[y]][ch[pre[y]][] == y] = x;
//if y is not the root, link x with its grandparent
pre[x] = pre[y];
ch[x][d] = y;
pre[y] = x;
} void splay(int u, int dest){
//root u to root dest
while(pre[u] != dest){
if(pre[pre[u]] == dest) rotate(u, ch[pre[u]][] == u);
else{
int y = pre[u];
int d = ch[pre[y]][] == y;
if(ch[y][d] == u){//zig-zag
rotate(u, !d);
rotate(u, d);
}else{
rotate(y, d);//zig-zig
rotate(u, d);
}
}
}
if(!dest) root = u;
} int insert(int k){
int u = root;
while(ch[u][key[u] < k]){
if(key[u] == k) return splay(u, ), ;
u = ch[u][key[u] < k];
}
if(key[u] == k) return splay(u, ), ;
new_node(ch[u][key[u] < k], u, k);
splay(ch[u][key[u] < k], );
return ;
} int get_pre(int x){
int tem = ch[x][];
if(!tem) return inf;
while(ch[tem][]) tem = ch[tem][];
return key[x] - key[tem];
} int get_next(int x){
int tem = ch[x][];
if(tem == ) return inf;
while(ch[tem][]) tem = ch[tem][];
return key[tem] - key[x];
} int main(){
//freopen("in.txt", "r", stdin);
while(~scanf("%d", &n)){
root = size = ;
int ans = ;
for(int i = ; i <= n; i++){
int num;
if(scanf("%d", &num) == EOF) num = ;
if(i == ){
ans += num;
new_node(root, , num);
continue;
}
if(!insert(num)) continue;
int a = get_next(root);
int b = get_pre(root);
ans += min(a, b);
}
printf("%d\n", ans);
}
return ;
}