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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章