题目链接:http://hihocoder.com/problemset/problem/1078
我的代码:
1 #include <iostream> 2 #include <algorithm> 3 4 using namespace std; 5 6 #define MAXN 100005 7 8 int w[MAXN]; 9 10 struct segNode 11 { 12 int left, right, sum; 13 bool lazy; 14 }; 15 16 struct segTree 17 { 18 segNode t[4*MAXN]; 19 void build(int i, int l, int r) 20 { 21 t[i].left = l; 22 t[i].right = r; 23 t[i].lazy = false; 24 if(l<r) 25 { 26 int m = (l+r)/2; 27 build(2*i, l, m); 28 build(2*i+1, m+1, r); 29 t[i].sum = t[2*i].sum+t[2*i+1].sum; 30 } 31 else t[i].sum = w[l]; 32 } 33 int query(int i, int l, int r) 34 { 35 if(t[i].lazy) pushdown(i); 36 if(t[i].left==l&&t[i].right==r) return t[i].sum; 37 int m = (t[i].left+t[i].right)/2; 38 if(l>m) return query(2*i+1, l, r); 39 if(r<=m) return query(2*i, l, r); 40 return query(2*i, l, m)+query(2*i+1, m+1, r); 41 } 42 void update(int i, int l, int r, int v) 43 { 44 if(t[i].lazy) pushdown(i); 45 if(t[i].left==l&&t[i].right==r) 46 { 47 t[i].sum = (t[i].right-t[i].left+1)*v; 48 t[i].lazy = true; 49 } 50 else 51 { 52 int m = (t[i].left+t[i].right)/2; 53 if(l>m) update(2*i+1, l, r, v); 54 else if(r<=m) update(2*i, l, r, v); 55 else 56 { 57 update(2*i, l, m, v); 58 update(2*i+1, m+1, r, v); 59 } 60 t[i].sum = t[2*i].sum+t[2*i+1].sum; 61 } 62 } 63 void pushdown(int i) 64 { 65 t[i].lazy = false; 66 if(t[i].left<t[i].right) 67 { 68 int l = t[i].right-t[i].left+1; 69 int ll = t[2*i].right-t[2*i].left+1; 70 int rl = t[2*i+1].right-t[2*i+1].left+1; 71 t[2*i].sum = t[i].sum/l*ll; 72 t[2*i+1].sum = t[i].sum/l*rl; 73 t[2*i].lazy = true; 74 t[2*i+1].lazy = true; 75 } 76 } 77 }tree; 78 79 int main() 80 { 81 int n, q; 82 bool op; 83 while(cin>>n) 84 { 85 for(int i=1; i<=n; ++i) cin>>w[i]; 86 tree.build(1, 1, n); 87 cin>>q; 88 while(q--) 89 { 90 cin>>op; 91 if(op) 92 { 93 int l, r, v; 94 cin>>l>>r>>v; 95 tree.update(1, l, r, v); 96 } 97 else 98 { 99 int l, r; 100 cin>>l>>r; 101 cout<<tree.query(1, l, r)<<endl; 102 } 103 } 104 } 105 return 0; 106 }