码迷,mamicode.com
首页 > 其他好文 > 详细

UVA 11922(Splay

时间:2015-09-06 17:49:44      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:

题目:维护一个序列,支持将一段数翻转并插到最后的操作,最后输出整个序列。

思路:直接套的大白模板,第一次用splay,贴一下。。

技术分享
/*
*@author:  Cwind
*http://www.cnblogs.com/Cw-trip/
*/
#include <bits/stdc++.h>
#define pb push_back
#define PB pop_back
#define bk back()
#define se second
#define fs first
#define IINF (1<<29)
#define sq(x) (x)*(x)
#define eps 0.000000001
#define clr(x) memset((x),0,sizeof (x))
using namespace std;
typedef long long ll;
typedef pair<ll,ll> P;

const int maxp=1e6+3000;
struct Node{
    int s;
    int val;
    bool flip;
    Node *ch[2];
    Node():s(0),flip(0){}
    int cmp(const int k)const {
        int d=k-ch[0]->s;
        if(d==1) return -1;
        else return d>0;
    }
    void maintain(){
        s=ch[0]->s+ch[1]->s+1;
    }
    void pushdown(){
        if(flip){
            flip=0;
            swap(ch[0],ch[1]);
            ch[0]->flip^=1;
            ch[1]->flip^=1;
        }
    }
}pool[maxp];
Node *null=new Node();
int ph=0;
Node *newNode(){
    Node *n=&pool[ph++];
    n->flip=n->s=0;
    return n;
}
void rotate(Node *&o,int d){
    Node *k=o->ch[d^1];
    o->ch[d^1]=k->ch[d];
    k->ch[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->ch[0]->s+1;
    if(d!=-1){
        Node *p=o->ch[d];
        p->pushdown();
        int d2=p->cmp(k);
        int k2=(d2==0?k:k-p->ch[0]->s-1);
        if(d2!=-1){
            splay(p->ch[d2],k2);
            if(d==d2) rotate(o,d^1);else rotate(o->ch[d],d);
        }
        rotate(o,d^1);
    }
}
Node* merge(Node *left,Node *right){
    splay(left,left->s);
    left->ch[1]=right;
    left->maintain();
    return left;
}
void split(Node *o,int k,Node *&left,Node *&right){
    splay(o,k);
    left=o;
    right=o->ch[1];
    o->ch[1]=null;
    left->maintain();
}
int num=0;
Node *build(int sz){
    if(sz==0) return null;
    Node *n=newNode();
    n->ch[0]=build(sz/2);
    n->val=num++;
    n->ch[1]=build(sz-sz/2-1);
    n->maintain();
    return n;
}
void print(Node *n){
    if(n==null) return;
    n->pushdown();
    print(n->ch[0]);
    if(n->val!=0)printf("%d\n",n->val);
    print(n->ch[1]);
}
int n,m;
int main(){
    freopen("/home/files/CppFiles/in","r",stdin);
    //freopen("defense.in","r",stdin);
    //freopen("defense.out","w",stdout);
    cin>>n>>m;
    Node *root=build(n+1);
    while(m--){
        int a,b;
        scanf("%d%d",&a,&b);
        Node *l,*r,*m,*o;
        split(root,a,l,o);
        split(o,b-a+1,m,r);
        m->flip^=1;
        root=merge(merge(l,r),m);
    }
    print(root);
    return 0;
}
View Code

 

UVA 11922(Splay

标签:

原文地址:http://www.cnblogs.com/Cw-trip/p/4786265.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!