hdu 4578 Transformation [线段树 区间更新]

本文介绍了一种使用线段树解决特定区间操作问题的方法,包括加法、乘法和赋值操作,并通过维护Σ1、Σ2、Σ3等来高效计算区间和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:
一个长度为n的数列a,初始全为0,对这个数列进行m个操作,操作格式如下:
op x y c
op=1: a[i] += c, i=x,x+1,...,y
op=2: a[i] *= c, i=x,x+1,...,y
op=3: a[i] = c, i=x,x+1,...,y
op=4: 输出sum=a[x]+a[x+1]+...+a[y]
思路:
考虑用线段树,对set,mul,add的处理顺序为set->mul->add。
对于一段序列a[x],a[x+1],...,a[y]记
Sigma1(a[i]) = a[x] + a[x+1] +...+ a[y]
Sigma2(a[i]) = a[x]^2 + a[x+1]^2 +...+ a[y]^2
Sigma3(a[i]) = a[x]^3 + a[x+1]^3 +...+ a[y]^3
那么,
Sigma1(n*a[i]+p)
= (n*a[x]+p) + (n*a[x+1]+p) +...+ (n*a[y]+p)
= n*(a[x]+a[x+1]+...+a[y]) + p*(y-x+1)
= n*Sigma1(a[i])
Sigma2(n*a[i]+p)
= (n*a[x]+p)^2 + (n*a[x+1]+p)^2 +...+ (n*a[y]+p)^2
= n*n*(a[x]^2+a[x+1]^2+...+a[y]^2) + 2*n*p*(a[x]+a[x+1]+...+a[y]) + p*p*(y-x+1)
= n*n*Sigma2(a[i]) + 2*n*p*Sigma1(a[i]) + p*p*(y-x+1)
Sigma3(n*a[i]+p)
= (n*a[x]+p) + (n*a[x+1]+p) +...+ (n*a[y]+p)
= n*n*n*(a[x]^3+a[x+1]^3+...+a[y]^3) + 3*n*n*p*(a[x]^2+a[x+1]^2+...+a[y]^2) + 3*n*p*p*(a[x]+a[x+1]+...+a[y]) + p*p*p*(y-x+1)
= n*n*n*Sigma3(a[i]) + 3*n*n*p*Sigma2(a[i]) + 3*n*p*p*Sigma1(a[i]) + p*p*p*(y-x+1)
这样就很容易求解了。

maintain(o):
 if setv then cope o with setv
 else if R>L then cope o with lo and ro
 else cope o as leaf node
 cope o with mulv then addv
pushdown(o):
 if setv then push setv down
 if mulv then push mulv down
 if addv then push addv down
update:
 if [y1,y2] contains [L,R]
  do update directly
 else
  pushdown
  if y1 <= M then update(lo) else maintain(lo)
  if y2 > M then update(ro) else maintain(ro)
  maintain(o)




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值