P1471 方差 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
感谢个人中心 - 洛谷(转载这位大佬的图片)
下面我的代码
#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
//typedef __long double128 LL;//2的128
typedef long long ll; //2的64
// 1e9,, 1e19,,1e38
//#define long double long long
const int N=100010;
long double a[N];
struct node{
int l,r;
long double sum1,sum2,lazy;
long double len;
}tr[N*4];
int n,m;
void pushup(int u){
tr[u].sum1=tr[u*2].sum1+tr[u*2+1].sum1;
tr[u].sum2=tr[u*2].sum2+tr[u*2+1].sum2;
}
void build(int u,int l,int r){
tr[u]={l,r};
tr[u].len=(r-l+1);
if(l==r){
tr[u].sum1=a[l];
tr[u].sum2=a[l]*a[l];
tr[u].lazy=0;
return;
}
int mid=(l+r)/2;
build(u*2,l,mid);
build(u*2+1,mid+1,r);
pushup(u);
}
void change(int u,long double k){
tr[u].sum2=tr[u].sum2+2*k*tr[u].sum1+tr[u].len*k*k;
tr[u].sum1+=(tr[u].len*k);
tr[u].lazy+=k;
}
void pushdown(int u){
if(tr[u].lazy==0) return;
change(u*2,tr[u].lazy);
change(u*2+1,tr[u].lazy);
tr[u].lazy=0;
return;
}
void change(int u,int l,int r,long double k){
if(tr[u].l>=l&&tr[u].r<=r){
tr[u].sum2=tr[u].sum2+2*k*tr[u].sum1+tr[u].len*k*k;
tr[u].sum1+=(tr[u].len*k);
tr[u].lazy+=k;
return;
}
pushdown(u);
int mid=(tr[u].l+tr[u].r)/2;
if(l<=mid) change(u*2,l,r,k);
if(r>mid) change(u*2+1,l,r,k);
pushup(u);
}
long double query(int u,int l,int r){
if(tr[u].l>=l&&tr[u].r<=r){
return tr[u].sum1;
}
pushdown(u);
long double mid=(tr[u].l+tr[u].r)/2;
long double sum=0;
if(l<=mid) sum+=query(u*2,l,r);
if(r>mid) sum+=query(u*2+1,l,r);
return sum;
}
long double query(int u,int l,int r,long double k){
if(tr[u].l>=l&&tr[u].r<=r){
return tr[u].sum2;
}
pushdown(u);
long double mid=(tr[u].l+tr[u].r)/2;
long double sum=0;
if(l<=mid) sum+=query(u*2,l,r,1);
if(r>mid) sum+=query(u*2+1,l,r,1);
return sum;
}
void solve()
{ cin>>n>>m;
for(int i=1;i<=n;i++)
cin>>a[i];
build(1,1,n);
while(m--){
int ok,l,r;
cin>>ok>>l>>r;
if(ok==1){
long double k;
cin>>k;
change(1,l,r,k);
}
else if(ok==2){
long double tk=(query(1,l,r)*1.0000000)/(r-l+1);
cout<<fixed<<setprecision(4)<<tk<<endl;
}else if(ok==3){
long double tz=query(1,l,r);
long double ty=query(1,l,r,1);
long double ts=(ty*1.000000)/(r-l+1)-(tz*1.000000)/(r-l+1)*(tz*1.000000)/(r-l+1);
ts=abs(ts);
cout<<fixed<<setprecision(4)<<ts<<endl;
}
}
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
solve();
return 0;
}