标签:dig mat ring queue char style ack code ios
前几天做了一个简单题
通过读题我们很容易看出他就是让我们求这么一个东西:
\(\displaystyle\sum_{i = 1}^n \sum_{j = i + 1}^{n} (a_i - a_j)^2\)
我们把后边的完全平方公式展开就是:
\(\displaystyle\sum_{i = 1}^n \sum_{j = i + 1}^{n} a_i^2 -2a_ia_J + a_j^2\)
显然我们还可以把 \(a_i^2\)提出来
\(\displaystyle\sum_{i = 1}^n (n - i)a_i^2-2a_i\sum_{j = i + 1}^{n}a_J + \sum_{j = i + 1}^{n}a_j^2\)
显然后边的\(a_j\) 和\(a_j^2\)我们可以提前用前缀和处理
我们用sum[i]表示对a[i]数组的前缀和,用sum2表示对\(a[i]^2\)的前缀和
那么原来的式子就能化成:
\(\displaystyle\sum_{i = 1}^n (n - i)a_i^2-2a_i*(sum[n] - sum[i])+ (sum2[n]-sum2[i])\)
最后的时候注意取膜就行了
#include <set>
#include <map>
#include <cmath>
#include <queue>
#include <stack>
#include <cstdio>
#include <string>
#include <vector>
#include <cstring>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <algorithm>
#define ll long long
#define N 500010
#define M 1010
using namespace std;
const int mod = 1000000007;
int n;
ll a[N], sum[N], sum2[N];
ll read() {
ll s = 0, f = 0; char ch = getchar();
while (!isdigit(ch)) f |= (ch == ‘-‘), ch = getchar();
while (isdigit(ch)) s = s * 10 + (ch ^ 48), ch = getchar();
return f ? -s : s;
}
int main() {
n = read();
for (int i = 1; i <= n; i++) {
a[i] = read();
sum[i] = (sum[i - 1] + a[i]) % mod;
sum2[i] = (sum2[i - 1] + (a[i] * a[i]) % mod) % mod;
}
ll ans = 0;
for (int i = 1; i <= n; i++) {
ll x1 = ((n - i) * ((a[i] * a[i]) % mod)) % mod;
ll x2 = ((2 * a[i] % mod) * ((sum[n] - sum[i] + mod) % mod)) % mod;
ll x3 = (sum2[n] - sum2[i] + mod) % mod;
ll x = (x1 - x2 + x3 + mod) % mod;
ans = (ans + x) % mod;
}
cout << ans;
}
标签:dig mat ring queue char style ack code ios
原文地址:https://www.cnblogs.com/zzz-hhh/p/12774262.html