HNOI 2002 营业额统计(Splay入门)

第一次写splay。。

首先你必须要明确一些事情 -> 坚信splay不难, 好吧, 下面推荐一篇博客, 作为入门, 之后再做一下这道题(其实并不需要splay), 就可以开始splay之路了

这道题没什么好解释, 裸题, 中文的, 不需要解释了

参考了cxlove的博客

code->

#include <bits/stdc++.h>
using namespace std;

#define N 100005
#define oo 1<<30
#define rep(i, s, t) for(int i = s; i <= t; ++i)

int n, tot, root, key[N];

struct Splay{
	int fa[N], ch[N][2];

	void newnode(int &r, int father, int w) {
		r = ++tot;
		fa[r] = father;
		key[r] = w;
		ch[r][0] = 0;
		ch[r][1] = 0;
	}

	void rotate(int x, int kind) {
		int y = fa[x];

		ch[y][!kind] = ch[x][kind]; fa[ch[y][!kind]] = y;

		if(fa[y]) ch[fa[y]][ch[fa[y]][1]==y] = x;

		fa[x] = fa[y]; fa[y] = x; ch[x][kind] = y;
	}

	void splay(int u) {
		while(fa[u]) {
			if(!fa[fa[u]]) rotate(u, ch[fa[u]][0] == u);

			else {
				int v = fa[u];
				int kind = ch[fa[v]][0]==v;

				if(ch[v][kind] == u) rotate(u, !kind), rotate(u, kind);
				else rotate(v, kind), rotate(u, kind);
			}
		}
		root = u;
	}
	int insert(int k) {
		int u = root;
		if(key[root] ^ k) {
			while(ch[u][key[u]<k]) {
				if(key[u] == k) {
					//cout<<k<<"$"<<endl;
					splay(u);
					return 0;
				}
				u = ch[u][key[u]<k];
			}
			newnode(ch[u][key[u]<k], u, k);
			splay(ch[u][key[u]<k]);
			return 1;
		}
		return 0;
	}

	int geta(int x) {
		int t = ch[x][0];
		if(!t) return oo;
		while(ch[t][1]) t = ch[t][1];
		return abs(key[t] - key[x]);
	}
	int getb(int x) {
		int t = ch[x][1];
		if(!t) return oo;
		while(ch[t][0]) t = ch[t][0];
		return abs(key[t] - key[x]);
	}
}sp;

int main() {
#ifndef ONLINE_JUDGE
	freopen("data.in", "r", stdin);
	freopen("result.out", "w", stdout);
#endif
	int x, res = 0;
	scanf("%d", &n);
	scanf("%d", &x);
	sp.newnode(root, 0, x);
	res += x;
	rep(i, 2, n) {
		scanf("%d", &x);
		if(sp.insert(x)) {
			res += min(sp.geta(root), sp.getb(root));
		//	cout<<res<<endl;
		}
	}
	cout<<res<<endl;
	return 0;
}


posted @ 2016-08-09 18:06  pbvrvnq  阅读(112)  评论(0编辑  收藏  举报