1104 Sum of Number Segments (20分)

题目链接:1104 Sum of Number Segments

题意:

求数组的全部连续子序列的和。
下标1为首个元素

思路1:

求每个数在全部子序列中出现的次数。设子序列的首尾指针为f,r.若a[i]在子序列中那么,i必在[f,r]中,f有1, 2… i种可能,共i种,r有 i ,i + 1…n种可能共n-i + 1种可能所以a[i]出现的次数为i*(n - i + 1),因此全部连续子序列的和为a[i]*i*(n-i+1) 。

#include <iostream>
#include <cstdio>
#include <cstring>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

using namespace std;
const int maxn = 100010;
double a[maxn] = {0}, sum = 0;
int n;
int main(int argc, char** argv) {
	
	scanf("%d", &n);
	for (int i = 1; i <= n; i++) {
		scanf("%lf", &a[i]);
		sum += a[i] * i * (n - i + 1);
	}
	printf("%.2f\n", sum);
	return 0;
}


思路2:

按照题意模拟,依次计算序列和,可以先看规律
设n=4
1 2 3 4
a1
a1 a2
a1 a2 a3
a1 a2 a3 a4
以a1为首的子序列和为1,2,3,4列之和,以a2为首的子序列和为2,3,4列之和,依次类推,因此输入的时候就可以令每列的值为a[i] = a[i] * (n - i + 1).
然后在逆序求出以每个元素为首的序列和,为后(n - i + 1)列元素之和,然后在相加。

问题

但是思路二结果有一个测试案例不对,百思不得其姐–应该没有溢出问题,实在想不通,难道是精度问题吗。附上代码

#include <iostream>
#include <cstdio>
#include <cstring>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

using namespace std;
const int maxn = 500010;
double a[maxn] = {0}, sum = 0;
int n;
int main(int argc, char** argv) {
	
	scanf("%d", &n);
	for (int i = 1; i <= n; i++) {
		scanf("%lf", &a[i]);
		a[i] = (n - i + 1) * a[i];
	}
	for (int i = n - 1; i > 0; i--) {
		a[i] += a[i + 1];
		sum += a[i]; 
	}
	printf("%.2f\n", sum + a[n]);
	return 0;
}
发布了17 篇原创文章 · 获赞 0 · 访问量 457

猜你喜欢

转载自blog.csdn.net/qq_37866436/article/details/104167980
今日推荐