题目链接:
点击打开链接
基础线段树,思想题目里面写了,照着这个思路写就可以了。自己写了一遍。
代码:
#include<iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
#include <cmath>
using namespace std;
const int maxn = 100005;
int n;
int a[maxn],lazy[maxn];
long long tree[maxn*4];
void build(int root,int l,int r){
if(l == r){
tree[root] = a[l];
return;
}
int mid = (l+r) >> 1;
build(root*2, l, mid);
build(root*2+1, mid+1, r);
tree[root] = tree[root*2] + tree[root*2+1];
}
void push_down(int root,int l,int r){
if(lazy[root]){
int mid = (l+r)>>1;
tree[root*2] = (mid-l+1) * lazy[root];
tree[root*2+1] = (r-mid) * lazy[root];
lazy[root*2] = lazy[root*2+1] = lazy[root];
lazy[root] = 0;
}
}
long long cal(int root,int l,int r,int x,int y){
if(x<=l && r<=y){
return tree[root];
}
push_down(root,l,r);
int mid = (l+r) >> 1;
int ans1=0,ans2=0;
if(x<=mid) ans1 = cal(root*2,l,mid,x,y);
if(mid<y) ans2 = cal(root*2+1,mid+1,r,x,y);
return ans1+ans2;
}
void change(int root,int l,int r,int x,int y,int num){
if(x<=l && r<=y){
tree[root] = num*(r-l+1);
lazy[root] = num;
return;
}
push_down(root,l,r);
int mid = (l+r)>>1;
if(x<=mid) change(root*2, l, mid, x, y, num);
if(y>mid) change(root*2+1, mid+1, r, x, y, num);
tree[root] = tree[root*2] + tree[root*2+1];
}
int main(){
scanf("%d",&n);
for(int i=1; i<=n; i++) scanf("%d",&a[i]);
memset(lazy,0,sizeof(lazy));
build(1,1,n);
int q,type;
scanf("%d",&q);
while(q--){
scanf("%d",&type);
if(type == 0){
int l,r;
scanf("%d%d",&l,&r);
printf("%lld\n",cal(1,1,n,l,r));
}
else {
int l,r,num;
scanf("%d%d%d",&l,&r,&num);
change(1,1,n,l,r,num);
}
}
return 0;
}