方差
题目大意:给一个 n n n 个元素的序列, m m m 次操作,其中有区间加更新,询问区间平均值,询问区间方差。
对于平均值,维护区间和就OK了。主要问题就在于区间方差,但其实我们将其式子展开就会发现妙处。
s 2 = 1 n ∑ i = 1 n ( a i − a ‾ ) 2 s^2=\frac{1}{n}\sum_{i=1}^n(a_i-\overline{a})^2 s2=n1∑i=1n(ai−a)2
s 2 = 1 n ∑ i = 1 n ( a i 2 + a ‾ 2 − 2 a i a ‾ ) s^2=\frac{1}{n}\sum_{i=1}^n(a_i^2+\overline{a}^2-2a_i\overline{a}) s2=n1∑i=1n(ai2+a2−2aia)
s 2 = a ‾ 2 + 1 n ∑ i = 1 n a i 2 − 1 n ∑ i = 1 2 a i a ‾ s^2=\overline{a}^2+\frac{1}{n}\sum_{i=1}^na_i^2-\frac{1}{n}\sum_{i=1}2a_i\overline{a} s2=a2+n1∑i=1nai2−n1∑i=12aia
s 2 = a ‾ 2 + 1 n ∑ i = 1 n a i 2 − 2 a ‾ S [ l , r ] s^2=\overline{a}^2+\frac{1}{n}\sum_{i=1}^na_i^2-2\overline{a}S[l,r] s2=a2+n1∑i=1nai2−2aS[l,r]
S[l,r]代表[l,r]的区间和
那么我们只需要维护一个区间和与区间平方和即可
#include <bits/stdc++.h>
#define lson rt<<1
#define rson rt<<1|1
using namespace std;
typedef long long ll;
const int N = 1e5 + 5;
const double eps = 1e-9;
int n, m;
double tree1[N << 2], tree2[N << 2], lz[N << 2];
void push_up(int rt) {
tree1[rt] = tree1[lson] + tree1[rson];
tree2[rt] = tree2[lson] + tree2[rson];
}
void push_down(int rt, int l, int r) {
int mid = l + r >> 1;
lz[lson] += lz[rt];
lz[rson] += lz[rt];
tree2[lson] += (mid - l + 1) * lz[rt] * lz[rt] + 2 * tree1[lson] * lz[rt];
tree2[rson] += (r - mid) * lz[rt] * lz[rt] + 2 * tree1[rson] * lz[rt];
tree1[lson] += (mid - l + 1) * lz[rt];
tree1[rson] += (r - mid) * lz[rt];
lz[rt] = 0;
}
void build(int rt, int l, int r) {
if (l == r) {
scanf("%lf", &tree1[rt]);
tree2[rt] = tree1[rt] * tree1[rt];
return ;
}
int mid = l + r >> 1;
build(lson, l, mid);
build(rson, mid + 1, r);
push_up(rt);
}
void update(int rt, int l, int r, int L, int R, double k) {
if (L <= l && r <= R) {
tree2[rt] += (r - l + 1) * k * k + 2 * tree1[rt] * k;
tree1[rt] += (r - l + 1) * k;
lz[rt] += k;
return ;
}
if (fabs(lz[rt]) > eps) push_down(rt, l, r);
int mid = l + r >> 1;
if (mid >= L) update(lson, l, mid, L, R, k);
if (mid < R) update(rson, mid + 1, r, L, R, k);
push_up(rt);
}
pair<double, double> query(int rt, int l, int r, int L, int R) {
if (L <= l && r <= R) return {tree1[rt], tree2[rt]};
push_down(rt, l, r);
int mid = l + r >> 1;
double sum1 = 0, sum2 = 0;
if (mid >= L) {
pair<double, double> t = query(lson, l, mid, L, R);
sum1 += t.first; sum2 += t.second;
}
if (mid < R) {
pair<double, double> t = query(rson, mid + 1, r, L, R);
sum1 += t.first; sum2 += t.second;
}
return {sum1, sum2};
}
int main() {
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
scanf("%d%d", &n, &m);
build(1, 1, n);
while(m--) {
int op, l, r;
double k;
scanf("%d", &op);
if (op == 1) {
scanf("%d%d%lf", &l, &r, &k);
update(1, 1, n, l, r, k);
}
else if (op == 2) {
scanf("%d%d", &l, &r);
printf("%.4f\n", query(1, 1, n, l, r).first / (r - l + 1));
}
else {
scanf("%d%d", &l, &r);
pair<double, double> t = query(1, 1, n, l, r);
double ave = t.first / (r - l + 1);
printf("%.4f\n", ave * ave + (t.second - 2 * ave * t.first) / (r - l + 1));
}
}
}