BZOJ3249 : [ioi2013]game

线段树套Treap

外层的线段树需要动态开节点

内层Treap需要注意的是,相同y坐标的点不一定是同一个点,所以需要再次离散

空间$O(n\log n)$

时间$O(n\log^2n)$

 

#include<cstdio>

#include<cstdlib>

#define N 705000

typedef long long ll;

int n,m,q,x1,y1,x2,y2,op,l[N],r[N],tot,R,A,B;ll w,ans,loc,c,d,inf;

inline void read(int&a){char ch;while(!(((ch=getchar())>='0')&&(ch<='9')));a=ch-'0';while(((ch=getchar())>='0')&&(ch<='9'))a*=10,a+=ch-'0';}

ll gcd(ll a,ll b){if(!a&&!b)return 0;if(!a)return b;return b?gcd(b,a%b):a;}

struct node{

  int p;ll val,v,sum;node*l,*r;

  node(){val=v=sum=p=0;l=r=NULL;}

  inline void up(){sum=gcd(v,gcd(l->sum,r->sum));}

}*blank=new(node),*T[N];

inline void Rotatel(node*&x){node*y=x->r;x->r=y->l;x->up();y->l=x;y->up();x=y;}

inline void Rotater(node*&x){node*y=x->l;x->l=y->r;x->up();y->r=x;y->up();x=y;}

void Ins(node*&x){

  if(x==blank){

    x=new(node);x->val=loc;x->l=x->r=blank;x->v=x->sum=w;x->p=std::rand();

    return;

  }

  if(loc==x->val){x->v=w;x->up();return;}

  if(loc<x->val){

    Ins(x->l);

    if(x->l->p>x->p)Rotater(x);else x->up();

  }else{

    Ins(x->r);

    if(x->r->p>x->p)Rotatel(x);else x->up();

  }

}

void Ask(node*&x,ll a,ll b){

  if(x==blank)return;

  if(c<=a&&b<=d){ans=gcd(ans,x->sum);return;}

  if(c<=x->val&&x->val<=d)ans=gcd(ans,x->v);

  if(c<x->val)Ask(x->l,a,x->val-1);

  if(d>x->val)Ask(x->r,x->val+1,b);

}

void change(int&x,int a,int b){

  if(!x)x=++tot,T[x]=blank;

  Ins(T[x]);

  if(a==b)return;

  int mid=(a+b)>>1;

  x1<=mid?change(l[x],a,mid):change(r[x],mid+1,b);

}

void ask(int x,int a,int b){

  if(!x)return;

  if(x1<=a&&b<=x2){Ask(T[x],1,inf);return;}

  int mid=(a+b)>>1;

  if(x1<=mid)ask(l[x],a,mid);

  if(x2>mid)ask(r[x],mid+1,b);

}

int main(){

  blank->l=blank->r=blank;

  read(n),read(m),read(q);

  inf=(ll)(m+1)*n;

  while(q--){

    read(op),read(x1),read(y1);x1++,y1++;

    if(op==1)loc=(ll)y1*n+x1,scanf("%lld",&w),change(R,1,n);

    else{

      read(x2),read(y2),x2++,y2++;

      c=(ll)y1*n+1,d=(ll)(y2+1)*n;

      ans=0,ask(R,1,n),printf("%lld\n",ans);

    }

  }

  return 0;

}

  

 

你可能感兴趣的:(game)