POJ---线段树---=-=
应该是今夜的世界杯前的最后一题了吧
又是个区间更新-增减 区间查询-求和 类型的题目
连废话都不想打上去了 有点烦那
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 // 线段树 区间更新--增减 区间查询--求和 2 3 #include <iostream> 4 using namespace std; 5 6 const int size = 100010; 7 typedef long long LL; 8 LL ans; 9 struct data 10 { 11 int l; 12 int r; 13 LL flag; 14 LL sum; 15 }tree[size*3]; 16 17 void create( int root , int l , int r ) 18 { 19 int mid = (l+r)>>1; 20 tree[root].l = l; 21 tree[root].r = r; 22 tree[root].flag = 0; 23 if( l==r ) 24 { 25 scanf( "%lld",&tree[root].sum ); 26 return; 27 } 28 create( root<<1 , l , mid ); 29 create( root<<1|1 , mid+1 , r ); 30 tree[root].sum = tree[root<<1].sum + tree[root<<1|1].sum; 31 } 32 33 void pushDown( int root , int len ) 34 { 35 tree[root<<1].flag += tree[root].flag; 36 tree[root<<1].sum+=(len-len/2)*tree[root].flag; 37 tree[root<<1|1].flag += tree[root].flag; 38 tree[root<<1|1].sum+=(len/2)*tree[root].flag; 39 tree[root].flag = 0; 40 } 41 42 void update( int root , int L , int R , LL num ) 43 { 44 int mid = ( tree[root].l + tree[root].r )>>1; 45 if( tree[root].l>=L && tree[root].r<=R ) 46 { 47 tree[root].sum+=num*(tree[root].r-tree[root].l+1); 48 tree[root].flag += num; 49 return; 50 } 51 if( tree[root].flag!=0 ) 52 { 53 pushDown( root , (tree[root].r-tree[root].l+1) ); 54 } 55 if( L<=mid ) 56 { 57 update( root<<1 , L , R , num ); 58 } 59 if( R>=mid+1 ) 60 { 61 update( root<<1|1 , L , R , num ); 62 } 63 tree[root].sum = tree[root<<1].sum + tree[root<<1|1].sum; 64 } 65 66 void query( int root , int L , int R ) 67 { 68 int mid = ( tree[root].l+tree[root].r )>>1; 69 if( tree[root].l>=L && tree[root].r<=R ) 70 { 71 ans+=tree[root].sum; 72 return; 73 } 74 if( tree[root].flag!=0 ) 75 { 76 pushDown( root , (tree[root].r-tree[root].l+1) ); 77 } 78 if( L<=mid ) 79 { 80 query( root<<1 , L , R ); 81 } 82 if( R>=mid+1 ) 83 { 84 query( root<<1|1 , L , R ); 85 } 86 tree[root].sum = tree[root<<1].sum + tree[root<<1|1].sum; 87 } 88 89 int main() 90 { 91 int L , R; 92 int n , m; 93 LL num; 94 char ch; 95 while( ~scanf("%d %d",&n,&m) ) 96 { 97 create( 1 , 1 , n ); 98 while( m-- ) 99 { 100 getchar(); 101 scanf( "%c",&ch ); 102 if( ch == 'C' ) 103 { 104 scanf( "%d %d %lld",&L,&R,&num ); 105 update( 1 , L , R , num ); 106 } 107 else 108 { 109 ans = 0; 110 scanf( "%d %d",&L,&R ); 111 query( 1 , L , R ); 112 printf( "%lld\n",ans ); 113 } 114 } 115 } 116 return 0; 117 }
just follow your heart