Luogu4927 梦美与线段树(线段树+概率期望)

  每个节点被经过的概率即为该区间和/总区间和。那么所需要计算的东西就是每个节点的平方和了。修改对于某个节点的影响是使其增加2sum·l·x+l2x2。那么考虑对子树的影响,其中Σl2是定值,修改后Σsum·l会增加Σl2x。维护一下就好。

  懒得纠结爆long long的问题了,被卡90算了。

// luogu-judger-enable-o2
// luogu-judger-enable-o2
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
int read()
{
int x=,f=;char c=getchar();
while (c<''||c>'') {if (c=='-') f=-;c=getchar();}
while (c>=''&&c<='') x=(x<<)+(x<<)+(c^),c=getchar();
return x*f;
}
#define N 100010
#define P 998244353
#define ll long long
int n,m,a[N],L[N<<],R[N<<],sum[N<<],ssqr[N<<],ssum[N<<],slen[N<<],lazy[N<<];
int ksm(int a,int k)
{
int s=;
for (;k;k>>=,a=1ll*a*a%P) if (k&) s=1ll*s*a%P;
return s;
}
int inv(int a){return ksm(a,P-);}
void inc(int &x,int y){x+=y;if (x>=P) x-=P;}
void up(int k)
{
sum[k]=(sum[k<<]+sum[k<<|])%P;
ssum[k]=((ssum[k<<]+ssum[k<<|])%P+1ll*sum[k]*(R[k]-L[k]+)%P)%P;
ssqr[k]=((ssqr[k<<]+ssqr[k<<|])%P+1ll*sum[k]*sum[k]%P)%P;
slen[k]=((slen[k<<]+slen[k<<|])%P+1ll*(R[k]-L[k]+)*(R[k]-L[k]+)%P)%P;
}
void build(int k,int l,int r)
{
L[k]=l,R[k]=r;
if (l==r) {ssum[k]=sum[k]=a[l];ssqr[k]=1ll*a[l]*a[l]%P;slen[k]=;return;}
int mid=l+r>>;
build(k<<,l,mid);
build(k<<|,mid+,r);
up(k);
}
void work(int k,int x)
{
inc(sum[k],1ll*x*(R[k]-L[k]+)%P);
inc(ssqr[k],(1ll*x*x%P*slen[k]%P+2ll*x%P*ssum[k]%P)%P);
inc(ssum[k],1ll*slen[k]*x%P);
inc(lazy[k],x);
}
void down(int k)
{
work(k<<,lazy[k]),work(k<<|,lazy[k]);
lazy[k]=;
}
void modify(int k,int l,int r,int x)
{
if (L[k]==l&&R[k]==r) {work(k,x);return;}
if (lazy[k]) down(k);
int mid=L[k]+R[k]>>;
if (r<=mid) modify(k<<,l,r,x);
else if (l>mid) modify(k<<|,l,r,x);
else modify(k<<,l,mid,x),modify(k<<|,mid+,r,x);
up(k);
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("d.in","r",stdin);
freopen("d.out","w",stdout);
const char LL[]="%I64d\n";
#else
const char LL[]="%lld\n";
#endif
n=read(),m=read();
for (int i=;i<=n;i++) a[i]=read();
build(,,n);
while (m--)
{
int op=read();
if (op==)
{
int x=read(),y=read(),z=read();
modify(,x,y,z);
}
else printf("%d\n",1ll*ssqr[]*inv(sum[])%P);
}
return ;
}
上一篇:CodeForces - 138C: Mushroom Gnomes - 2 (线段树&概率&排序)


下一篇:P3924 康娜的线段树(期望)