暴力:一半测试点TLE
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 100010;
int n;
double a[N], s[N];
double sum;
int main()
{
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%lf", &a[i]);
s[i] = s[i-1] + a[i];
}
for (int i = 1; i <= n; i++)
{
for (int j = i; j <= n; j++)
{
sum += s[j] - s[i-1];
}
}
printf("%.2lf\n", sum);
return 0;
}
要包含这个端点,左边端点可以选 1~i
,右边端点选i~n
注意精度为long double
,精度为18,中间可能会溢出,所以要先乘long double
N*N = 1e10
double
精度15, 位数1e30
printf("%.2Lf")
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
long double res = 0; //要用long double ,否则精度可能不够
for (int i = 1; i <= n; i++)
{
long double x;
cin >> x;
//第i个数出现字段的总和,左端点 1~i, 右端点 i~n
res += x * i * (n-i+1); //先乘long double 型,否则精度可能溢出
}
printf("%.2Lf\n", res);
return 0;
}