bzoj 1588 营业额统计

splay求前驱和后继。

//#include <bits/stdc++.h>
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <cstring>
#include <cmath>

using namespace std;

#define LL long long 
#define inf 0x3f3f3f3f
#define MP make_pair
#define pii pair<int, int>
#define N 100010
#define M 200020

int pre[N], ch[N][2], key[N];
int tot, root;

int creat(int p, int val){
	int k = ++tot;
	key[k] = val;
	pre[k] = p;
	ch[k][0] = ch[k][1] = 0;
	return k;
}
void rot(int x){
	int y = pre[x], d = ch[y][1] == x;
	ch[y][d] = ch[x][!d];
	if(ch[x][!d]) pre[ch[x][!d]] = y;
	ch[x][!d] = y;
	pre[x] = pre[y];
	pre[y] = x;
	if(pre[x]) ch[pre[x]][ch[pre[x]][1] == y] = x;
//	push_up(y);
}
void splay(int x, int goal){
	while(pre[x] != goal){
		int f = pre[x], ff = pre[f];
		if(ff == goal)
			rot(x);
		else if((ch[ff][1] == f) == (ch[f][1] == x))
			rot(f), rot(x);
		else rot(x), rot(x);
	}
	if(goal == 0) root = x;
}
bool insert(int k){
	if(root == 0){
		root = creat(0, k);
		return 1;
	}
	int x = root;
	while(ch[x][key[x]<k]){
		if(key[x] == k){
			splay(x, 0);
			return 0;
		}
		x = ch[x][key[x]<k];
	}
	if(key[x] == k){
		splay(x, 0);
		return 0;
	}
	ch[x][key[x]<k] = creat(x, k);
	splay(ch[x][key[x]<k], 0);
	return 1;
}
int find_pre(int x){
	int t = ch[x][0];
	if(t == 0) return -inf;
	while(ch[t][1])
		t = ch[t][1];
	return key[t];
}
int find_suf(int x){
	int t = ch[x][1];
	if(t == 0) return inf;
	while(ch[t][0])
		t = ch[t][0];
	return key[t];
}
int main(){
	int n;
	scanf("%d", &n);
	tot = root = 0;
	LL ans = 0;
	while(n--){
		int v;
		if(scanf("%d", &v) == EOF) v = 0;
		if(root == 0){
			ans += v;
			insert(v);
			continue;
		}
		if(!insert(v)) continue;
		int ret = min(key[root] - find_pre(root), find_suf(root) - key[root]);
		ans += ret;
	}
	printf("%lld\n", ans);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值