题意 给出一段初始化全为1的区间 后面可以一段一段更改成 1 或 2 或3 问最后整段区间的和是多少
思路:标准线段树区间和模版题
1 #include<cstdio> 2 #include<algorithm> 3 #include<set> 4 #include<vector> 5 #include<cstring> 6 #include<iostream> 7 using namespace std; 8 const int maxn=1e5+7; 9 struct Node{ 10 int l,r,sum; 11 int lazy; 12 void update(int val){ 13 sum=(r-l+1)*val; 14 lazy=val; 15 16 } 17 }tree[maxn*4]; 18 void push_up(int x){ 19 tree[x].sum=tree[x<<1].sum+tree[x<<1|1].sum; 20 } 21 void push_down(int x){ 22 if(tree[x].lazy!=0){ 23 tree[x<<1].update(tree[x].lazy); 24 tree[x<<1|1].update(tree[x].lazy); 25 tree[x].lazy=0; 26 } 27 } 28 void build(int x,int l,int r){ 29 tree[x].l=l,tree[x].r=r; 30 tree[x].sum=tree[x].lazy=0; 31 if(l==r){ 32 tree[x].sum=1; 33 } 34 else { 35 int mid=l+r>>1; 36 build(x<<1,l,mid); 37 build(x<<1|1,mid+1,r); 38 push_down(x); 39 } 40 } 41 void update(int x,int l,int r,int c){ 42 int L=tree[x].l,R=tree[x].r; 43 if(R<=r&&L>=l){ 44 tree[x].update(c); 45 } 46 else { 47 int mid=L+R>>1; 48 push_down(x); 49 if(mid>=l)update(x<<1,l,r,c); 50 if(mid<r)update(x<<1|1,l,r,c); 51 push_up(x); 52 } 53 } 54 long long query(int x,int l,int r){ 55 int L=tree[x].l,R=tree[x].r; 56 if(R<=r&&L>=l){ 57 return tree[x].sum; 58 } 59 else { 60 int mid=L+R>>1; 61 long long ans=0; 62 //push_down(x); 63 if(mid>=l)ans+=query(x<<1,l,r); 64 if(mid<r)ans+=query(x<<1|1,l,r); 65 return ans; 66 } 67 } 68 int main(){ 69 int t,kase=1; 70 scanf("%d",&t); 71 while(t--){ 72 int n,q; 73 scanf("%d%d",&n,&q); 74 build(1,1,n); 75 for(int i=0;i<q;i++){ 76 int x,y,z; 77 scanf("%d%d%d",&x,&y,&z); 78 update(1,x,y,z); 79 } 80 printf("Case %d: The total value of the hook is %lld. ",kase++,query(1,1,n)); 81 } 82 return 0; 83 }