写了一天的线段树,这道题主要说明一下sum是赋值的,不是累加的,并且在push_down的时候lazy也是赋值的。因可能对懒标记的理解还不是很透彻吧。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int Max = 1e5+10;
typedef long long ll;
struct Tree{
int L,R;
ll sum;
int lazy;
} tree[Max<<2];
void PushUp(int x)
{
tree[x].sum = tree[x<<1].sum+tree[x<<1|1].sum;
}
void pushdown(int x,int num)
{
if(tree[x].lazy){
tree[x<<1].sum=tree[x].lazy*(num-(num/2));
tree[x<<1|1].sum=tree[x].lazy*(num/2);
tree[x<<1].lazy = tree[x].lazy;
tree[x<<1|1].lazy=tree[x].lazy;
tree[x].lazy=0;
}
}
void build(int x,int l,int r)
{
tree[x].L=l;
tree[x].R=r;
tree[x].sum=0;
tree[x].lazy=0;
if(l==r){
tree[x].sum=1;return;
}
int mid = (l+r)>>1;
build(x<<1,l,mid);
build(x<<1|1,mid+1,r);
PushUp(x);
}
void update(int x,int l,int r,int val)
{
int L = tree[x].L,R=tree[x].R;
if(l<=L&&R<=r)
{
tree[x].lazy=val;
tree[x].sum=(ll)(R-L+1)*val;
return ;
}
pushdown(x,R-L+1);
int mid = (L+R)>>1;
if(l<=mid)
update(x<<1,l,r,val);
if(mid<r)
update(x<<1|1,l,r,val);
PushUp(x);
}
ll query(int x,int l,int r)
{
ll res = 0;
int L=tree[x].L,R=tree[x].R;
if(l<=L&&r>=R){
return tree[x].sum;
}
pushdown(x,R-L+1);
int mid = (L+R)>>1;
if(l<=mid)
res += query(x<<1,l,r);
if(mid<r)
res += query(x<<1|1,l,r);
return res;
}
int main()
{
int T,n,m,left,right,sum;
scanf("%d",&T);
int cnt = 0;
while(T--)
{
cnt++;
scanf("%d%d",&n,&m);
build(1,1,n);
while(m--)
{
scanf("%d%d%d",&left,&right,&sum);
update(1,left,right,sum);
}
printf("Case %d: The total value of the hook is %lld.
",cnt,query(1,1,n));
}
return 0;
}