版权声明:本文是博主乱写的文章,可以随便转载 https://blog.csdn.net/weixin_43768644/article/details/89362666
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1698
解题思路:每次操作将一段区间的值都修改为同一个值,最后求整个区间的总和。
普通的线段树区间修改。
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#define mid int m = l+r>>1;
#define lson rt<<1,l,m
#define rson rt<<1|1,m+1,r
using namespace std;
const int N = 1e5+5;
int tree[N<<2],lazy[N<<2];
void push_up(int rt)
{
tree[rt] = tree[rt<<1] + tree[rt<<1|1];
}
void push_down(int rt,int len)
{
tree[rt<<1] = lazy[rt]*(len-len/2);
tree[rt<<1|1] = lazy[rt]*(len/2);
lazy[rt<<1] = lazy[rt];
lazy[rt<<1|1] = lazy[rt];
lazy[rt] = 0;
}
void update(int L,int R,int x,int rt,int l,int r)
{
if (L<=l && r<=R){
tree[rt] = x*(r-l+1);
lazy[rt] = x;
return ;
}
if (lazy[rt]) push_down(rt,r-l+1);
mid;
if (L<=m) update(L,R,x,lson);
if (R>m) update(L,R,x,rson);
push_up(rt);
}
int query(int L,int R,int rt,int l,int r)
{
if (L<=l && r<=R){
return tree[rt];
}
if (lazy[rt]) push_down(rt,r-l+1);
mid;
int ans = 0;
if (L<=m) ans += query(L,R,lson);
if (R>m) ans += query(L,R,rson);
return ans;
}
void build(int rt,int l,int r)
{
if (l==r){
tree[rt] = 1;
return ;
}
mid;
build(lson);
build(rson);
push_up(rt);
}
int main()
{
int t,n,q,x,y,v,ica=0;
scanf("%d",&t);
while (t--){
memset(lazy,0,sizeof lazy);
scanf("%d %d",&n,&q);
build(1,1,n);
while (q--){
scanf("%d %d %d",&x,&y,&v);
update(x,y,v,1,1,n);
}
printf("Case %d: The total value of the hook is %d.\n",++ica,query(1,n,1,1,n));
}
return 0;
}