PAT Advanced 1104 Sum of Number Segments (20 )
题目描述

Input Specification:

Output Specification:

Sample Input:

Sample Output:

解题思路
找规律题,以N=5举例,求出每一列中的累积count观察规律。
第一列 5 4 3 2 1
第二列 5 8 6 4 2
第三列 5 8 9 6 3
第四列 5 8 9 8 4
第五列 5 8 9 8 5
不难看出,第i列第j个数=(N-j)*min(列数, j)。
得到这个规律花了1h,要是考试就凉凉。
还因为是用temp*i*j还是i*j*temp导致有两个点挂了,由于temp<1.0,先乘temp可以避免溢出(保存结果是double型),毕竟 i 和 j 都是<1e5,i先乘j则默认保存结果是int型后乘以temp才转化为double,这种小错误要尽量避免。
Code
- AC代码
#include<bits/stdc++.h>
using namespace std;
int main() {
//freopen("in.txt", "r", stdin);
int N;
cin >> N;
double temp, sum = 0;
for(int i = N, j = 1; i>=1; i--, j++) {
cin >> temp;
sum += temp*i*j;
}
printf("%.2f\n", sum);
return 0;
}
本文详细解析PATAdvanced1104题目,通过观察数列规律找到高效解题方法。以N=5为例,揭示了每列中累积count的变化规律,总结出第i列第j个数的计算公式,为解决类似数列求和问题提供了一种新的思路。
526

被折叠的 条评论
为什么被折叠?



