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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值