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


  • 相关阅读:
    PHP7还没学明白,PHP8就要来了, 能有多快?
    Linux ab 压力测试
    大公司为什么都有API网关?没你想的那么简单!
    mac安装的vagrant访问laraval欢迎页面,执行时间15秒,安装nfs挂载点(亲测可行)
    PHP操作Elasticsearch
    PHP OpenSSL扩展 对称加密
    为什么 select count(*) from t,在 InnoDB 引擎中比 MyISAM 慢?
    Redis哨兵机制
    未来三五年,社会上什么工作会更吃香呢?这几方面
    自己的 Doxyfile 模板
  • 原文地址:https://www.cnblogs.com/pbvrvnq/p/8530169.html
Copyright © 2020-2023  润新知