uva 11922 Permutation Transformer (splay树的分割及合并)

这是按ljr的splay写的

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
#include <string>
using namespace std;

struct Node{
	int val, flip, sum;
	Node* child[2];
	Node(int x = 0) : val(x){
		child[0] = child[1] = NULL;
		flip = sum = 0;
	}
	void pushdown(){
		if(flip){
			flip = 0;
			swap(child[0], child[1]);
			if(child[0] != NULL)
				child[0]->flip ^= 1;
			if(child[1] != NULL)
				child[1]->flip ^= 1;
		}
	}
	void maintain(){
		sum = 1;
		if(child[0] != NULL)	sum += child[0]->sum;
		if(child[1] != NULL)	sum += child[1]->sum;
	}
	int cmp (int v){
    	int d = v - (child[0] == NULL ? 0 : child[0]->sum);
    	if (d == 1) return -1;
    	return d <= 0 ? 0 : 1;
	}
};

void rotate(Node*& o, int d){                       // d = 1 右旋,d = 0 左旋 
	Node* k = o->child[d^1];
    o->child[d^1] = k->child[d];
    k->child[d] = o;
    o->maintain();
    k->maintain();
    o = k;
}


void splay(Node*& o, int k){
	o->pushdown();
	int d = o->cmp(k);
	if (d == 1) k -= (o->child[0] == NULL ? 0 : o->child[0]->sum) + 1;
    if (d != -1) {
        Node* p = o->child[d];
        p->pushdown();
        int d2 = p->cmp(k);
        int k2 = (d2 == 0 ? k : k - (p->child[0] == NULL ? 0 : p->child[0]->sum) - 1);
        if (d2 != -1) {
            splay(p->child[d2], k2);
            if (d == d2)
                rotate(o, d^1);
            else
                rotate(o->child[d], d);
        }
        rotate(o, d^1);
    }
}


void split(Node* o, int k, Node*& l, Node*& r){
	splay(o, k);
	l = o;
	r = o->child[1];
	o->child[1] = NULL;
	l->maintain();
}

void build(Node*& o, int l, int r){
	if(l > r)	return ;
	int mid = (l+r)/2;
	o = new Node(mid);
	build(o->child[0], l, mid-1);
	build(o->child[1], mid+1, r);
	o->maintain();
}

Node* merge(Node* l, Node* r){
	splay(l, l->sum);
	l->child[1] = r;
	l->maintain();
	return l;
}

void print(Node* root){
	root->pushdown();
	if(root->child[0] != NULL)
		print(root->child[0]);
	if(root->val)
	printf("%d\n",root->val);
	if(root->child[1]!= NULL)
		print(root->child[1]);
}

int main()
{
	//freopen("ztest.txt","r",stdin);
	int n, m;
	scanf("%d%d", &n, &m);
	Node* root = NULL;
	Node* o, *l, *r, *mid;
	build(root, 0, n);
	//print(root);
	for(int i = 1; i <= m; i++){
		int a, b;
		scanf("%d%d", &a, &b);
		split(root, a, l, o);
		split(o, b-a+1, mid, r);
		mid->flip ^= 1;
		root = merge(merge(l, r), mid);
	}
	print(root);
	return 0;
}
		

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值