您的位置:首页 > 大数据 > 人工智能

hdu3487 Play with Chain

2015-10-03 17:00 471 查看
自己写的第一颗splay。

http://acm.hdu.edu.cn/showproblem.php?pid=3487

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 3e5 + 10;
int pre[maxn], ch[maxn][2], key[maxn], size[maxn];
bool rev[maxn], ok;
int n, m, nodes;
int root;
char buf[15];

void new_node(int &u, int fa, int value){
u = ++nodes;
ch[u][0] = ch[u][1] = 0;
key[u] = value;
pre[u] = fa;
size[u] = size[ch[u][0]] = size[ch[u][1]] = 0;
rev[u] = 0;
}

void push_up(int u) { size[u] = 1 + size[ch[u][0]] + size[ch[u][1]]; }

void build(int l, int r, int &u, int fa){
if(r < l) return;
int mid = (l + r) >> 1;
new_node(u, fa, mid);
build(l, mid - 1, ch[u][0], u);
build(mid + 1, r, ch[u][1], u);
push_up(u);
}

void push_down(int u){
if(!size[u] || !rev[u]) return;
rev[ch[u][0]] ^= 1;
rev[ch[u][1]] ^= 1;
swap(ch[u][0], ch[u][1]);
rev[u] = 0;
}

void rotate(int u, int d){
int y = pre[u];
ch[y][!d] = ch[u][d];
if(pre[y]) ch[pre[y]][ch[pre[y]][1] == y] = u;
pre[ch[u][d]] = y;
ch[u][d] = y;
pre[u] = pre[y];
pre[y] = u;
push_up(y), push_up(u);
}

void splay(int u, int dest){
while(pre[u] != dest){
if(pre[pre[u]] == dest) { rotate(u, ch[pre[u]][0] == u); break; }
int y = pre[u];
int d = ch[pre[u]][0] == u;
if(ch[pre[y]][d] == y) rotate(u, d), rotate(u, !d);
else rotate(y, d), rotate(u, d);
}
if(!dest) root = u;
}

int get_kth(int u, int k){
push_down(u);
int tem = size[ch[u][0]];
if(tem + 1 == k) return u;
return tem >= k ? get_kth(ch[u][0], k) : get_kth(ch[u][1], k - tem - 1);
}

void reverse(int a, int b){
int x = get_kth(root, a);
int y = get_kth(root, b + 2);
splay(x, 0);
splay(y, root);
rev[ch[y][0]] ^= 1;
}

void cut(int a, int b, int c){
int x = get_kth(root, a);//get address
int y = get_kth(root, b + 2);
splay(x, 0);
splay(y, root);
int tem = ch[y][0];
ch[ch[root][1]][0] = 0;
push_up(ch[root][1]);
push_up(root);//maintain size, cut interval[a,b]
int z = get_kth(root, c + 1);
splay(z, 0);
int nex = get_kth(root, 2 + size[ch[root][0]]);
splay(nex, root);
pre[tem] = nex;//link
ch[nex][0] = tem;
push_up(nex);
push_up(root);
}

void print(int u){
if(!size[u]) return;
push_down(u);
print(ch[u][0]);
if(key[u] >= 1 && key[u] <= n) ok ? putchar(' ') : ok ^= 1, printf("%d", key[u]);
print(ch[u][1]);
push_up(u);
}

int main(){
freopen("in.txt", "r", stdin);
while(~scanf("%d%d", &n, &m) && (n + 1)){
ok = nodes = 0;
pre[0] = ch[0][0] = ch[0][1] = size[0] = 0;//null node
build(0, n + 1, root, 0);
for(int i = 1, x, y, z; i <= m; i++){
scanf("%s%d%d", buf, &x, &y);
if(buf[0] == 'C') scanf("%d", &z), cut(x, y, z);
else reverse(x, y);
}
print(root), putchar('\n');
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: