1. 程式人生 > >bzoj3212: Pku3468 A Simple Problem with Integers(線段樹)

bzoj3212: Pku3468 A Simple Problem with Integers(線段樹)

while printf scan font geo main post align sim

3212: Pku3468 A Simple Problem with Integers

題目:傳送門


題解:

   感謝Rose_max大佬的傾情相(推)助(水題)

   一起打線段樹啊~~~~


代碼:

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<cstdlib>
 4 #include<cmath>
 5 #include<algorithm>
 6 using namespace std;
 7
typedef long long LL; 8 struct node 9 { 10 int l,r,lc,rc; 11 LL lazy,c;bool v; 12 }tr[410000];int trlen; 13 void update(int now) 14 { 15 int lc=tr[now].lc,rc=tr[now].rc; 16 tr[lc].c+=tr[now].lazy*(tr[lc].r-tr[lc].l+1);tr[lc].lazy+=tr[now].lazy;tr[lc].v=true; 17 tr[rc].c+=tr[now].lazy*(tr[rc].r-tr[rc].l+1
);tr[rc].lazy+=tr[now].lazy;tr[rc].v=true; 18 tr[now].lazy=0;tr[now].v=false; 19 } 20 void bt(int l,int r) 21 { 22 int now=++trlen; 23 tr[now].l=l;tr[now].r=r;tr[now].c=0; 24 tr[now].lc=tr[now].rc=-1;tr[now].lazy=0;tr[now].v=false; 25 if(l<r) 26 { 27 int mid=(l+r)/2
; 28 tr[now].lc=trlen+1;bt(l,mid); 29 tr[now].rc=trlen+1;bt(mid+1,r); 30 } 31 } 32 void add(int now,int l,int r,int c) 33 { 34 if(tr[now].l==l && r==tr[now].r){tr[now].c+=LL(c)*(tr[now].r-tr[now].l+1);tr[now].lazy+=c;tr[now].v=true;return ;} 35 int lc=tr[now].lc,rc=tr[now].rc,mid=(tr[now].l+tr[now].r)/2; 36 if(tr[now].v)update(now); 37 if(r<=mid)add(lc,l,r,c); 38 else if(mid+1<=l)add(rc,l,r,c); 39 else add(lc,l,mid,c),add(rc,mid+1,r,c); 40 tr[now].c=(tr[lc].c+tr[rc].c); 41 } 42 LL getsum(int now,int l,int r) 43 { 44 if(tr[now].l==l && r==tr[now].r)return tr[now].c; 45 int lc=tr[now].lc,rc=tr[now].rc,mid=(tr[now].l+tr[now].r)/2; 46 if(tr[now].v)update(now); 47 if(r<=mid)return getsum(lc,l,r); 48 else if(mid+1<=l)return getsum(rc,l,r); 49 else return getsum(lc,l,mid)+getsum(rc,mid+1,r); 50 } 51 int main() 52 { 53 int n,m,x,y; 54 scanf("%d%d",&n,&m);bt(1,n);for(int i=1;i<=n;i++)scanf("%d",&x),add(1,i,i,x); 55 while(m--) 56 { 57 char s[5]; 58 scanf("%s%d%d",s+1,&x,&y);if(x>y)swap(x,y); 59 if(s[1]==C){LL c;scanf("%lld",&c);add(1,x,y,c);} 60 else printf("%lld\n",getsum(1,x,y)); 61 } 62 return 0; 63 }

bzoj3212: Pku3468 A Simple Problem with Integers(線段樹)