P2234 [HNOI2002]营业额统计【Splay】

传送门
给定长度为 N N N的数组,表示营业额
一 天 的 最 小 波 动 值 = min ⁡ { ∣ 该天以前某一天的营业额 − 该天营业额 ∣ } 一天的最小波动值 = \min\{|\text{该天以前某一天的营业额}-\text{该天营业额}|\} 一天的最小波动值=min{∣该天以前某一天的营业额−该天营业额∣}
求每一天的营业额
第一天为它本身

分析

假设当前的营业额为 x x x,我们要知道以前的,小于 x x x的最大值,大于 x x x的最小
这就是前驱和后继了
所以我们要动态维护前驱后继
注意,非严格前驱后继!可以等于,所以做些小变化。
详细看 f i n d _ p r e , f i n d _ n x t find\_pre,find\_nxt find_pre,find_nxt的那个“=”号
行! 那就用 S p l a y Splay Splay了

代码

//P2234
/*
  @Author: YooQ
*/
#include <bits/stdc++.h>
using namespace std;
#define sc scanf
#define pr printf
#define ll long long
#define FILE_OUT freopen("out", "w", stdout);
#define FILE_IN freopen("in", "r", stdin);
#define debug(x) cout << #x << ": " << x << "\n";
#define AC 0
#define WA 1
#define INF 0x3f3f3f3f
const ll MAX_N = 1e6+5;
const ll MOD = 1e9+7;
int N, M, K;

struct Tr {
	int k, cnt, sz, fa;
	int son[2];
	int& l = son[0];
	int& r = son[1];
}tr[MAX_N];
int root = 0;
int indx = 0;

void push_up(int rt) {
	tr[rt].sz = tr[tr[rt].l].sz + tr[tr[rt].r].sz + tr[rt].cnt;
}

int which(int x) {
	return tr[tr[x].fa].son[1] == x;
}

void rotate(int x) {
	int p = tr[x].fa;
	int q = tr[p].fa;
	int side = which(x);
	
	tr[tr[p].son[side] = tr[x].son[side^1]].fa = p;
	tr[tr[x].son[side^1] = p].fa = x;
	tr[x].fa = q;
	
	if (q) {
		tr[q].son[tr[q].son[1] == p] = x;
	}
	
	push_up(p);
	push_up(x);
}

void splay(int x, int tar) {
	for (int p; (p = tr[x].fa) != tar; rotate(x)) {
		if (tr[p].fa != tar) rotate(which(x) == which(p) ? p : x);
	}
	if (!tar) root = x;
}

int find(int x) {
	int rt = root;
	while (tr[rt].son[x > tr[rt].k] && x != tr[rt].k) {
		rt = tr[rt].son[x > tr[rt].k];
	}
	splay(rt, 0);
	return rt;
}

int find_pre(int x) {
	int rt = find(x);
	if (tr[rt].k <= x) return rt;
	rt = tr[rt].l;
	while (tr[rt].r) {
		rt = tr[rt].r;
	}
	return rt;
}

int find_nxt(int x) {
	int rt = find(x);
	if (tr[rt].k >= x) return rt;
	rt = tr[rt].r;
	while (tr[rt].l) {
		rt = tr[rt].l;
	}
	return rt;
}

void insert(int x) {
	int rt = root, pre = 0;
	while (rt && x != tr[rt].k) {
		pre = rt;
		rt = tr[rt].son[x > tr[rt].k];
	}
	if (rt) {
		++tr[rt].cnt;
		splay(rt, 0);
		return;
	}
	rt = ++indx;
	tr[rt].fa = pre;
	tr[rt].k = x;
	tr[rt].sz = tr[rt].cnt = 1;
	if (pre) tr[pre].son[x > tr[pre].k] = rt;
	splay(rt, 0);
}

void solve(){
	sc("%d", &N);
	int ans = 0;
	insert(-1e9);
	insert(1e9);
	
	int x;
	for (int i = 1; i <= N; ++i) {
		sc("%d", &x);
		if (i == 1) ans += x;
		else ans += min(abs(x - tr[find_pre(x)].k), abs(x - tr[find_nxt(x)].k));
		insert(x);
	}
	pr("%d\n", ans);
}

signed main()
{
	#ifndef ONLINE_JUDGE
	//FILE_IN
	FILE_OUT
	#endif
	int T = 1;//cin >> T;
	while (T--) solve();

	return AC;
}

上一篇:文艺平衡树


下一篇:P1486 [NOI2004] 郁闷的出纳员【Splay】