H -- Variance
Time Limit:1s Memory Limit:128MByte
Submissions:309Solved:91
DESCRIPTION
An array with length n is given.
You should support 2 types of operations.
1 x y change the x-th element to y.
2 l r print the variance of the elements with indices l, l + 1, ... , r.
As the result may not be an integer, you need print the result after multiplying (r-l+1)^2.
The index of the array is from 1.
INPUT
The first line is two integer n, m(1 <= n, m <= 2^{16}), indicating the length of the array and the number of operations.The second line is n integers, indicating the array. The elements of the array
0<=ai<=1040<=ai<=104.The following m lines are the operations. It must be either1 x yor2 l r
OUTPUT
For each query, print the result.
SAMPLE INPUT
4 41 2 3 42 1 41 2 42 1 42 2 4
SAMPLE OUTPUT
20242
SOLUTION
求方差,简化公式为(r-l+1)*S2(l~r的区间平方和)-S1(l~r的区间和)^2 ,所以很明显用线段树维护一下就好了,可以用一个线段树求同时S1,S2。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define inf 0x6fffffff
#define LL long long
using namespace std;
LL sum2[66600<<3],sum[66600<<3],s1,s2;
void pushup(int rt){
sum[rt]=sum[rt<<1]+sum[rt<<1|1];
sum2[rt]=sum2[rt<<1]+sum2[rt<<1|1];
}
void build(int l,int r,int rt){
if(l==r){
scanf("%d",sum+rt);
sum2[rt]=sum[rt]*sum[rt];
return;
}
int m=(l+r)>>1;
build(lson);
build(rson);
pushup(rt);
}
void update(int L,int R,int c,int l,int r,int rt){
if(L<=l&&R>=r){
sum[rt]=c;
sum2[rt]=c*c;
return;
}
int m=(l+r)>>1;
if(m>=L)update(L,R,c,lson);
if(m<R)update(L,R,c,rson);
pushup(rt);
}
void query(int L,int R,int l,int r,int rt){
if(L<=l&&R>=r){
s1+=sum[rt];
s2+=sum2[rt];
return;
}
int m=(l+r)>>1;
if(L<=m)query(L,R,lson);
if(R>m)query(L,R,rson);
}
int main(){
int n,m;
cin>>n>>m;
build(1,n,1);
while(m--){
int k,l,r,c;//cout<<"asd"<<endl;
LL s;
scanf("%d%d%d",&k,&l,&r);
if(k==1){
update(l,l,r,1,n,1);//其实这里参数表为(l,r,1,n,1) 就行了,因为套的模板,所以没有改
}
else{
s1=0;s2=0;
query(l,r,1,n,1);
// cout<<s2<<s1<<endl;
s=(r-l+1)*s2+s1*s1-2*s1*s1;
printf("%lld\n",s);
}
}
return 0;
}