基本上敲的模板
功能:区间更新,区间查询
自己随意开发。。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #include "iostream" 2 using namespace std; 3 #define lson l,m,rt<<1 4 #define rson m+1,r,rt<<1|1 5 #define bug cout << "bug!!!" << endl; 6 const int MAXN = 100010; 7 8 int sum[MAXN<<2]; 9 int p[MAXN<<2]; 10 11 //更新父亲 12 void PushUp(int rt) 13 { 14 sum[rt] = sum[rt<<1] + sum[rt<<1|1]; 15 } 16 17 //下放 18 void PushDown(int rt,int m) 19 { 20 if (p[rt]) { 21 p[rt<<1] = p[rt<<1|1] = p[rt]; 22 sum[rt<<1] = (m-(m>>1)) * p[rt]; 23 sum[rt<<1|1] = (m >> 1) * p[rt]; 24 p[rt] = 0; 25 } 26 } 27 28 void build(int l,int r, int rt) 29 { 30 if (l == r) { 31 cin >> p[rt]; 32 sum[rt] = p[rt]; 33 return; 34 } 35 int m = (l+r)>>1; 36 build(lson); 37 build(rson); 38 PushUp(rt); 39 } 40 41 //区间更新 42 void update(int L,int R,int c,int l,int r,int rt) 43 { 44 if (L <= l && r <= R) { 45 p[rt] = c; 46 sum[rt] = c*(r-l+1); 47 return; 48 } 49 PushDown(rt,r-l+1); 50 int m = (l+r)>>1; 51 if (L <= m) update(L,R,c,lson); 52 if (R > m) update(L,R,c,rson); 53 PushUp(rt); 54 } 55 56 //区间查询 57 int query(int L, int R,int l,int r,int rt) 58 { 59 if(L <= l && R >= r) { 60 return sum[rt]; 61 } 62 PushDown(rt,r-l+1);//比如rt存的1-4的和 而查询2-5 1-4就需要下放 63 int m = (l + r) >> 1; 64 int re = 0; 65 if (L <= m) re += query(L,R,lson); 66 if (R > m) re += query(L,R,rson); 67 return re; 68 } 69 70 int main() 71 { 72 int n; 73 cin >> n; 74 build(1,n,1); 75 int t; 76 cin >> t; 77 for (int i = 0;i < t;++ i) { 78 int ok; 79 cin >> ok; 80 if (ok) { 81 int p1,p2,c; 82 cin >> p1 >> p2 >> c; 83 update(p1,p2,c,1,n,1); 84 } 85 else { 86 int p1,p2; 87 cin >> p1 >> p2; 88 cout << query(p1,p2,1,n,1) << endl; 89 } 90 } 91 }