1. 程式人生 > >[均攤複雜度線段樹] Codeforces #438D. The Child and Sequence

[均攤複雜度線段樹] Codeforces #438D. The Child and Sequence

水~~~

#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=200005;
typedef unsigned long long  uLL; 
struct node{
    node* ch[2];
    uLL sum,_max;   
    node(uLL t1=0,uLL t2=0,node* t3=0){ sum=t1; _max=t2; ch[0]=ch[1]=t3; }
    void maintain(){
        _max=max(ch[0]->_max,ch[1
]->_max); sum=ch[0]->sum+ch[1]->sum; } } *root; typedef node* P_node; P_node Build(int L,int R){ P_node p=new node(); if(L==R){ scanf("%d",&p->sum); p->_max=p->sum; return p; } int mid=(L+R)>>1; p->ch[0]=Build(L,mid); p->ch[1
]=Build(mid+1,R); p->maintain(); return p; } void Updata(P_node p,int L,int R,int pos,int val){ if(pos<L||R<pos) return; if(L==R){ p->sum=p->_max=val; return; } int mid=(L+R)>>1; Updata(p->ch[0],L,mid,pos,val); Updata(p->ch[1],mid+1,R,pos,val); p->maintain(); } void
Updata(P_node p,int L,int R,int qL,int qR,int Mod){ if(qR<L||R<qL||p->_max<Mod) return; if(L==R){ p->_max=(p->sum%=Mod); return; } int mid=(L+R)>>1; Updata(p->ch[0],L,mid,qL,qR,Mod); Updata(p->ch[1],mid+1,R,qL,qR,Mod); p->maintain(); } uLL Query(P_node p,int L,int R,int qL,int qR){ if(qR<L||R<qL) return 0; if(qL<=L&&R<=qR) return p->sum; int mid=(L+R)>>1; return Query(p->ch[0],L,mid,qL,qR)+Query(p->ch[1],mid+1,R,qL,qR); } int n,Q; int main(){ freopen("cf438D.in","r",stdin); freopen("cf438D.out","w",stdout); scanf("%d%d",&n,&Q); root=Build(1,n); while(Q--){ int _type,x,y,z; scanf("%d",&_type); if(_type==1){ scanf("%d%d",&x,&y); printf("%I64d\n",Query(root,1,n,x,y)); } else if(_type==2){ scanf("%d%d%d",&x,&y,&z); Updata(root,1,n,x,y,z); } else if(_type==3){ scanf("%d%d",&x,&y); Updata(root,1,n,x,y); } } return 0; }