题目链接:P1471 方差
2024.1.4 补充了对求方差的说明
大致题意
给定一个长度为n的01序列, 下标从0开始, 需要实现如下五种操作.
1 l r c
,表示将第l到第r项每项加上 c,c 为一实数。2 l r
,表示求出第l到第r项这一子数列的平均数。3 l r
,表示求出第l到第r项这一子数列的方差。
解题思路
这就是一道数学推公式+线段树维护区间 的典型例题!
在我判断浮点数是否为0的时候大意了啊, 写了1E-5, 结果WA了半天.
由于题目中需要求某个序列的方差. 根据方差公示
v
a
r
=
∑
(
x
i
−
m
e
a
n
)
2
n
=
∑
(
x
i
2
−
2
×
x
i
×
m
e
a
n
+
m
e
a
n
2
)
n
=
∑
x
i
2
−
2
∑
x
i
×
m
e
a
n
+
m
e
a
n
2
n
var=\frac{\sum(x_i-mean)^2}{n}=\frac{\sum(x_i^2-2 \times x_i \times mean + mean^2)}{n} = \frac{\sum{x_i^2} - 2\sum{x_i} \times mean + mean^2}{n}
var=n∑(xi−mean)2=n∑(xi2−2×xi×mean+mean2)=n∑xi2−2∑xi×mean+mean2
其中
n
n
n表示区间长度,
m
e
a
n
mean
mean表示区间平均值.
根据 m e a n = ∑ x i n mean = \frac{\sum{x_i}}{n} mean=n∑xi 化简, 最终可得 v a r = ∑ x i 2 n − ( ∑ x i n ) 2 var=\frac{\sum{x_i^2}}{n} - (\frac{\sum{x_i}}{n})^2 var=n∑xi2−(n∑xi)2.
我们发现需要同时对子数组的区间和以及区间平方和进行维护.
AC代码
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 1; i <= (n); ++i)
using namespace std;
typedef long long ll;
const int N = 1E5 + 10;
double w[N];
struct node {
int l, r;
double val, fval;
double lazy;
}t[N << 2];
void pushdown(node& op, double lazy) {
op.fval += (op.r - op.l + 1) * lazy * lazy + 2.0 * lazy * op.val;
op.val += lazy * (op.r - op.l + 1);
op.lazy += lazy;
}
void pushdown(int x) {
if (abs(t[x].lazy) <= 1E-7) return; //精度要给高一些
pushdown(t[x << 1], t[x].lazy), pushdown(t[x << 1 | 1], t[x].lazy);
t[x].lazy = 0;
}
void pushup(int x) {
t[x].val = t[x << 1].val + t[x << 1 | 1].val;
t[x].fval = t[x << 1].fval + t[x << 1 | 1].fval;
}
void build(int l, int r, int x = 1) {
t[x] = { l, r, w[l], w[l] * w[l], 0 };
if (l == r) return;
int mid = l + r >> 1;
build(l, mid, x << 1), build(mid + 1, r, x << 1 | 1);
pushup(x);
}
void modify(int l, int r, double c, int x = 1) {
if (l <= t[x].l && r >= t[x].r) {
pushdown(t[x], c);
return;
}
pushdown(x);
int mid = t[x].l + t[x].r >> 1;
if (l <= mid) modify(l, r, c, x << 1);
if (r > mid) modify(l, r, c, x << 1 | 1);
pushup(x);
}
node ask(int l, int r, int x = 1) {
if (l <= t[x].l && r >= t[x].r) return t[x];
pushdown(x);
int mid = t[x].l + t[x].r >> 1;
if (r <= mid) return ask(l, r, x << 1);
if (l > mid) return ask(l, r, x << 1 | 1);
node res, left = ask(l, r, x << 1), right = ask(l, r, x << 1 | 1);
res.val = left.val + right.val;
res.fval = left.fval + right.fval;
return res;
}
int main()
{
int n, m; cin >> n >> m;
rep(i, n) scanf("%lf", &w[i]);
build(1, n);
while (m--) {
int k, l, r; scanf("%d %d %d", &k, &l, &r);
if (k == 1) {
double c; scanf("%lf", &c);
modify(l, r, c);
}
else if (k == 2) printf("%.4f\n", ask(l, r).val / (r - l + 1));
else {
auto temp = ask(l, r); double len = r - l + 1;
double s1 = temp.val, s2 = temp.fval;
double res = s2 / len - s1 / len * s1 / len;
printf("%.4f\n", res);
}
}
return 0;
}