• Hdoj 1003


    原题链接

    描述

    Given a sequence a[1],a[2],a[3]......a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14.

    输入描述

    The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000).

    输出描述

    For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the first one. Output a blank line between two cases.

    样例输入

    2
    5 6 -1 5 4 -7
    7 0 6 -1 1 -6 7 -5

    样例输出

    Case 1:
    14 1 4

    Case 2:
    7 1 6

    思路

    最大连续子列和问题,典型的动态规划。需要注意的是格式问题。
    首先找到状态转移方程sum[i] = max{sum[i-1] + a[i-1], a[i-1]},维护起始值即可确定开始点和结束点。
    实际上,也不需要开数组,sum和a随时变化也可以。这样能将空间复杂度降到O(1),而时间复杂度是O(n)。

    代码

    #include <bits/stdc++.h>   
    using namespace std;  
    
    int main()
    {
    	int n; cin >> n;
    	for(int ii = 0; ii < n; ii++)
    	{
    		int num; cin >> num;
    		int f = 0, l = 0, t = 0;
    		int max, sum;
    		cin >> max; sum = max;
    		for(int i = 1; i < num; i++)
    		{
    			int a;
    			cin >> a;
    			if(sum >= 0)
    			{
    				sum += a;
    			}
    			else
    			{
    				sum = a;
    				t = i;
    			}
    			if(sum > max)
    			{
    				max = sum;
    				f = t;
    				l = i;
    			}
    		}
    		printf("Case %d:
    %d %d %d
    ", ii + 1, max, f + 1, l + 1);
    		if(ii < n - 1) printf("
    ");
    	}
    }
    
  • 相关阅读:
    定时任务(收集)
    命令学习(收集)
    查看进程运行时间
    Linux 中挂载 ISO 文件
    9.已知三边计算三角形的面积公式
    8.输入一个大写字母,要求小写字母输出
    1.输出三个数中的最大值
    2.依次从大到小输出三个数
    3.计算1+2+3+....100=?
    4.计算1*2*3*4........*100=?
  • 原文地址:https://www.cnblogs.com/HackHarry/p/8365362.html
Copyright © 2020-2023  润新知