玲珑杯 H -- Variance(线段树)

本文介绍了一种使用线段树数据结构来高效解决数组区间方差查询问题的方法。通过对数组元素进行更新操作和查询指定区间内的方差,算法能够快速响应不同类型的操作请求。
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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值