• PAT (Basic Level) Practice 1049 数列的片段和 (20分) (我是菜菜找不出数学规律)


    1.题目

    给定一个正数数列,我们可以从中截取任意的连续的几个数,称为片段。例如,给定数列 { 0.1, 0.2, 0.3, 0.4 },我们有 (0.1) (0.1, 0.2) (0.1, 0.2, 0.3) (0.1, 0.2, 0.3, 0.4) (0.2) (0.2, 0.3) (0.2, 0.3, 0.4) (0.3) (0.3, 0.4) (0.4) 这 10 个片段。

    给定正整数数列,求出全部片段包含的所有的数之和。如本例中 10 个片段总和是 0.1 + 0.3 + 0.6 + 1.0 + 0.2 + 0.5 + 0.9 + 0.3 + 0.7 + 0.4 = 5.0。

    输入格式:

    输入第一行给出一个不超过 10​5​​ 的正整数 N,表示数列中数的个数,第二行给出 N 个不超过 1.0 的正数,是数列中的数,其间以空格分隔。

    输出格式:

    在一行中输出该序列所有片段包含的数之和,精确到小数点后 2 位。

    输入样例:

    4
    0.1 0.2 0.3 0.4
    

    输出样例:

    5.00

    2.题目分析

    参考(https://blog.csdn.net/weixin_41256413/article/details/81748332

    悄悄告诉你数学规律:

     

    3.代码

    普通遍历版(2个测试点超时)

    #include<iostream>
    #include<algorithm>
    #include<cstdio>
    using namespace std;
    double list[100001];
    int main()
    {
    	int n;
    	cin >> n;
    	for (int i = 0; i<n; i++)
    		cin >> list[i];
    	int t = 0;
    	double total = 0, count = 0, little = 0;
    	for (int i = 0; i<n; i++)
    	{
    		t = 0;
    		while (t != n)
    		{
    			for (int j = i; j <=t; j++)
    			{
    				little = little + list[j];
    			}
    			t++;
    		}
    		count = count + little;
    		little = 0;
    	}
    	printf("%.2f", count);
    }

    数学规律:

    #include<iostream>
    using namespace std;
    double list[100001];
    int main()
    {
    	int n;
    	cin >> n;
    	for (int i = 1; i <=n; i++)cin >> list[i];
    	double count = 0;
    	for (int i = 1; i <= n; i++)
    		count = count + list[i] * i*(n + 1 - i);
    	printf("%.2f", count);
    }

    改进:

    #include<iostream>
    using namespace std;
    int main()
    {
    	int n;
    	double count = 0,temp;
    	cin >> n;
    	for (int i = 1; i <= n; i++) { cin >> temp; count = count +temp * i*(n + 1 - i);}
    	printf("%.2f", count);
    }
  • 相关阅读:
    爬取豆瓣电影信息
    MongoDB的聚合操作以及与Python的交互
    matplotlib简单示例
    MongoDB基本操作
    K近邻算法
    Scrapy爬取博客园精华区内容
    爬虫失败
    Markdown基本使用方法
    UITableViewCell高度自适应变化
    KVO和NSNotification
  • 原文地址:https://www.cnblogs.com/Jason66661010/p/12788942.html
Copyright © 2020-2023  润新知