uva 12538
2016-03-28 22:09
387 查看
可持续化treap,merge与split时新建结点;
代码好丑……
#include<bits/stdc++.h> #define rep(i,k,n) for(int i=k;i<=(n);i++) using namespace std; const int maxn = 7000155; struct Treap { int ch[maxn][2], s[maxn], val[maxn], key[maxn], root[50005], tot, now, ccnt; char str[120]; Treap() { tot = 1; now = ccnt = 0; } void up(int x) { s[x] = s[ch[x][0]] + s[ch[x][1]] + 1; } int copy(int x) { int t = ++tot; s[t] = s[x]; ch[t][0] = ch[x][0]; ch[t][1] = ch[x][1]; val[t] = val[x]; key[t] = key[x]; return t; } int merge(int l, int r) { if(!l)return r; if(!r)return l; if(key[l] < key[r]) { int t = copy(l); ch[t][1] = merge(ch[l][1], r); up(t); return t; } else { int t = copy(r); ch[t][0] = merge(l, ch[r][0]); up(t); return t; } } void split(int x, int k, int &l, int &r) { if(s[x] <= k) { l = x, r = 0; return; } int ll, rr; int tmp = s[ch[x][0]]; int t = copy(x); if(k > tmp) { split(ch[x][1], k - tmp - 1, ll, rr); ch[t][1] = ll; l = t; r = rr; } else { split(ch[x][0], k, ll, rr); ch[t][0] = rr; r = t; l = ll; } up(t); return; } void build(int& t, int l, int r, int pre) { if(l > r)return; t = ++tot; int mid = (l + r) >> 1; val[t] = str[mid]; key[t] = rand() + pre; s[t] = 1; if(l == r)return; build(ch[t][0], l, mid - 1, key[t]); build(ch[t][1], mid + 1, r, key[t]); up(t); } void out(int x) { if(!x)return; out(ch[x][0]); putchar(val[x]); if(val[x] == 'c')ccnt++; out(ch[x][1]); } void debug(int x) { if(!x)return; debug(ch[x][0]); putchar(val[x]); debug(ch[x][1]); } } tp; int n, op, T, t, p, l, r, x; int l2, r2; int main() { // freopen("in.in", "r", stdin); // freopen("out.out", "w", stdout); scanf("%d", &T); while(T--) { scanf("%d", &op); if(op == 1) { tp.now++; scanf("%d", &p); scanf("%s", tp.str + 1); tp.build(t, 1, strlen(tp.str + 1), 0); //printf("build: ");tp.debug(t);printf("\n"); p -= tp.ccnt; if(!p) { tp.root[tp.now] = tp.merge(t, tp.root[tp.now - 1]); } else if(p == tp.s[tp.root[tp.now - 1]]) { tp.root[tp.now] = tp.merge(tp.root[tp.now - 1], t); } else { tp.split(tp.root[tp.now - 1], p, l, r); tp.root[tp.now] = tp.merge(tp.merge(l, t), r); } //printf("1: ");tp.debug(tp.root[tp.now]);printf("\n"); } if(op == 2) { tp.now++; scanf("%d%d", &p, &x); p -= tp.ccnt; x -= tp.ccnt; tp.split(tp.root[tp.now - 1], p - 1, l, r); tp.split(r, x, l2, r2); tp.root[tp.now] = tp.merge(l, r2); //printf("2: ");tp.debug(tp.root[tp.now]);printf("\n"); } if(op == 3) { scanf("%d%d%d", &t, &p, &x); t -= tp.ccnt; p -= tp.ccnt; x -= tp.ccnt; tp.split(tp.root[t], p - 1, l, r); tp.split(r, x, l2, r2); tp.out(l2); printf("\n"); } } //printf("\n\n");treap.debug(treap.root); }
代码好丑……