方差

题目大意:对于一个大小为 𝑛 的数集 {𝑎𝑖} ,设其平均值为 𝑥 =∑ 𝑎𝑖/𝑛 ,则它的方差为\(∑(𝑎𝑖−𝑥)^2/𝑛\) 。现在有一个数集,你需要求出这个数集的每个非空子集的方差之和对1e9 + 7 取模的结果

推式子可以得到:

\[\dfrac { \sum{a_i}^2} {n} - \dfrac {(\sum a_i)^2}{n^2}\]

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <bits/stdc++.h>
#define int long long
using namespace std;

const int N = 1e6 + 666, mod = 1e9 + 7;

int n, sum1, sum2, res;
int a[N], sum[N], fac[N];

inline int ksm(int a, int b)
{
int ret(1);
for (; b; b >>= 1)
{
if (b & 1) ret = ret * a % mod;
a = a * a % mod;
}
return ret;
}

inline void pres_dou()
{
fac[0] = 1;
for (int i = 1; i <= n; ++ i) fac[i] = fac[i - 1] * i % mod;
return;
}

inline int C(int x, int y)
{
if (x < y) return 0;
if (x == y || y == 0) return 1;
return fac[x] * ksm(fac[y] * fac[x - y] % mod, mod - 2) % mod;
}

inline int ifac(int x)
{
if (x == 1) return 1;
return ksm(x, mod - 2) % mod;
}

signed main()
{
int i, x, y;
n = read();
for (i = 1; i <= n; ++ i)
{
a[i] = read();
sum[i] = ( sum[i - 1] + a[i]) % mod;
}

for (i = 1; i <= n; ++ i)
{
(sum1 += a[i] * a[i] % mod) %= mod, (sum2 += 2 * a[i] * ((sum[n] - sum[i]) % mod + mod) % mod) %= mod;
}

pres_dou();

for (i = 2; i <= n; ++ i)
{

x = ifac(i), y = ifac(i * i % mod);

res += ((sum1 * C(n - 1, i - 1) % mod * x
- (sum1 * C(n - 1, i - 1) % mod + sum2 * C(n - 2, i - 2) % mod) * y + mod) % mod + mod) % mod;

res = res % mod;
}
put(res % mod);
return 0;
}