HDU 3487 Play with Chain

来源:互联网 发布:mysql登录失败 编辑:程序博客网 时间:2024/05/16 05:52

这道题是我用伸展树A掉的第一道题, 题目意思很简单:有n个数, 两个操作, CUT a b c把第a~b的数取出来, 然后放在新的序列的第c个数后面;FLIP a b, 把区间a到b反转。一系列操作之后输出最后的序列。

对于CAT 操作: 可以先把区间第a-1个数旋转到根节点, 然后再把b + 1旋转到根节点下, 这样区间[a, b]就变成了一颗子树, 接下来只要把这整棵子树拿下, 放在新的序列的c的后面就可以了。

对于FLIP 操作: 前面一样, 把[a, b], 弄成一颗子树, 然后加上懒惰标记就可以了。

OK附上代码

#include <cstdio>#include <cstring>using namespace std;const int N = 300007;int root, ch[N][2], fa[N], sz[N];int num[N];bool rev[N];void pushdown(int x){if(rev[x]){rev[x] = false;rev[ch[x][0]] ^= 1;rev[ch[x][1]] ^= 1;int t = ch[x][0];ch[x][0] = ch[x][1];ch[x][1] = t;}}void pushup(int x){sz[x] = 1 + sz[ch[x][0]] + sz[ch[x][1]];}void rotate(int x, bool f){int y = fa[x];int z = fa[y];pushdown(y);pushdown(x);ch[y][!f] = ch[x][f];fa[ch[x][f]] = y;fa[x] = z;if(z)ch[z][ch[z][1] == y] = x;ch[x][f] = y;fa[y] = x;pushup(y);}void splay(int x, int g){int y = fa[x];pushdown(x);while(y != g){int z = fa[y];bool f1 = (ch[y][0] == x);bool f2 = (ch[z][0] == y);if(z != g && f1 == f2)rotate(y, f1);rotate(x, f1);y = fa[x];}pushup(x);if(g == 0)root = x;}void rotateto(int x, int g){int r = root;pushdown(r);while(sz[ch[r][0]] != x){if(x < sz[ch[r][0]])r = ch[r][0];else{x -= sz[ch[r][0]] + 1;r = ch[r][1];}pushdown(r);}splay(r, g);}void toroot(int x){while(x){pushup(x);x = fa[x];}}int getpath(int x){int r = root;pushdown(r);while(sz[ch[r][0]] != x){if(x < sz[ch[r][0]])r = ch[r][0];else{x -= sz[ch[r][0]] + 1;r = ch[r][1];}pushdown(r);}return r;}void CAT(int a, int b, int c){rotateto(a - 1, 0);rotateto(b + 1, root);int y = ch[root][1];int x = ch[y][0];int tmp = sz[x];sz[y] -= tmp;sz[root] -= tmp;ch[y][0] = 0;fa[x] = 0;int z = getpath(c);bool f = true;y = ch[z][1];while(y){pushdown(y);z = y;f = false;y = ch[z][0];}fa[x] = z;ch[z][f] = x;toroot(fa[x]);}void FLIP(int a, int b){rotateto(a - 1, 0);rotateto(b + 1, root);int y = ch[root][1];int x = ch[y][0];rev[x] ^= 1;}int out[N];int ans;void dfs(int r){if(r == 0)return ;pushdown(r);if(ch[r][0] == 0 && ch[r][1] == 0){out[ans++] = num[r];return ;}dfs(ch[r][0]);out[ans++] = num[r];dfs(ch[r][1]);}int main(){int n, m;while(scanf("%d%d", &n , &m)){if(n == -1 || m == -1)break;//建树, 随便怎么建, 只要顺序不变就行root = n + 2;num[0] = 0;sz[0] = 0;fa[0] = 0;num[1] = 0;sz[1] = 1;fa[1] = 2;memset(ch, 0, sizeof(ch));memset(rev, false, sizeof(rev));for(int i = 2; i <= n + 1; i++){num[i] = i - 1;sz[i] = i;fa[i] = i + 1;ch[i][0] = i - 1;}num[n + 2] = n + 1;sz[n + 2] = n + 2;fa[n + 2] = 0;ch[n + 2][0] = n + 1;while(m--){char s[5];int a, b ,c;scanf("%s%d%d", s, &a, &b);if(s[0] == 'C'){scanf("%d", &c);CAT(a, b, c);}elseFLIP(a, b);}ans = 0;dfs(root);printf("%d", out[1]);for(int i = 2; i <= n; i++)printf(" %d", out[i]);puts("");}return 0;}



原创粉丝点击