1. 程式人生 > >A - 敵兵布陣 HDU - 1166 線段樹(多點修改當單點修改)

A - 敵兵布陣 HDU - 1166 線段樹(多點修改當單點修改)

scan () 線段 int uil 多點 upd ase include

線段樹板子題練手用

 1 #include<cstdio>
 2 using namespace std;
 3 const int maxn=5e4+8;
 4 int a[maxn],n;
 5 struct Node{
 6     int l,r;
 7     long long sum,lazy;
 8     void update(long long  val){
 9         sum+=1ll*(r-l+1)*val;
10         lazy+=val;
11     }
12 }tree[maxn*4];
13 void push_up(int x){
14 tree[x].sum=tree[x<<1].sum+tree[x<<1|1].sum; 15 } 16 void push_down(int x){ 17 int lazyval=tree[x].lazy; 18 if(lazyval){ 19 tree[x<<1].update(lazyval); 20 tree[x<<1|1].update(lazyval); 21 tree[x].lazy=0; 22 } 23 } 24 void build(int x,int
l,int r){ 25 tree[x].l=l,tree[x].r=r; 26 tree[x].sum=tree[x].lazy=0; 27 if(l==r){ 28 tree[x].sum=a[l]; 29 } 30 else { 31 int mid=l+r>>1; 32 build(x<<1,l,mid); 33 build(x<<1|1,mid+1,r); 34 push_up(x);
35 } 36 } 37 void update(int x,int l,int r,long long val){ 38 int L=tree[x].l,R=tree[x].r; 39 if(L>=l&&R<=r){ 40 tree[x].update(val); 41 } 42 else { 43 int mid=L+R>>1; 44 push_down(x); 45 if(mid>=l)update(x<<1,l,r,val); 46 if(mid<r)update(x<<1|1,l,r,val); 47 push_up(x); 48 } 49 } 50 long long query(int x,int l,int r){ 51 int L=tree[x].l,R=tree[x].r; 52 if(L>=l&&R<=r){ 53 return tree[x].sum; 54 } 55 else { 56 int mid=L+R>>1; 57 long long ans=0; 58 push_down(x); 59 if(mid>=l)ans+=query(x<<1,l,r); 60 if(mid<r)ans+=query(x<<1|1,l,r); 61 push_up(x); 62 return ans; 63 } 64 } 65 int main(){ 66 int t,kase=1; 67 scanf("%d",&t); 68 while(t--){ 69 int n; 70 printf("Case %d:\n",kase++); 71 scanf("%d",&n); 72 for(int i=1;i<=n;i++){ 73 scanf("%d",&a[i]); 74 } 75 build(1,1,n); 76 char op[10]; 77 while(scanf("%s",op)&&op[0]!=E){ 78 if(op[0]==Q){ 79 int l,r; 80 scanf("%d%d",&l,&r); 81 printf("%lld\n",query(1,l,r)); 82 } 83 else if(op[0]==A){ 84 int l,r,c; 85 scanf("%d%d",&l,&c); 86 update(1,l,l,c); 87 } 88 else { 89 int l,c; 90 scanf("%d%d",&l,&c); 91 update(1,l,l,-c); 92 } 93 } 94 } 95 return 0; 96 }

A - 敵兵布陣 HDU - 1166 線段樹(多點修改當單點修改)