题意:一根钩子原来每单位长度价值均为1,每次改变一段区间的价值,求处理后钩子的总价值。
思路:线段树区间更新,区间求和,裸裸的模板题。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int sum[500010],lazy[500010];
void pushup(int rt)
{
sum[rt]=sum[rt<<1]+sum[rt<<1|1];
}
void pushdown(int rt,int x)
{
if(lazy[rt]!=-1)
{
lazy[rt<<1]=lazy[rt<<1|1]=lazy[rt];
sum[rt<<1]=(x-(x>>1))*lazy[rt];
sum[rt<<1|1]=(x>>1)*lazy[rt];
lazy[rt]=-1;
}
}
void build(int l,int r,int rt)
{
lazy[rt]=-1;
sum[rt]=1;
if(l==r) return;
int m=(l+r)/2;
build(l,m,rt<<1);
build(m+1,r,rt<<1|1);
pushup(rt);
}
void update(int l,int r,int x,int L,int R,int rt)
{
if(l<=L&&R<=r)
{
lazy[rt]=x;
sum[rt]=x*(R-L+1);
return;
}
pushdown(rt,(R-L+1));
int m=(L+R)/2;
if(l<=m) update(l,r,x,L,m,rt<<1);
if(m<r) update(l,r,x,m+1,R,rt<<1|1);
pushup(rt);
}
int main()
{
int T,n,q,x,y,z,i,j,k=0;
while(scanf("%d",&T)!=EOF)
{
while(T--)
{
scanf("%d %d",&n,&q);
build(1,n,1);
while(q--){
scanf("%d %d %d",&x,&y,&z);
update(x,y,z,1,n,1);
}
printf("Case %d: The total value of the hook is %d.\n",++k,sum[1]);
}
}
return 0;
}
原文:http://blog.csdn.net/dominating413421391/article/details/44132243