06_最大连续和

问题来源:刘汝佳《算法竞赛入门经典--训练指南》 P61 问题8:

问题描述:给出一个长度为n的序列A1,A2,...,An,求一个连续子序列Ai,Ai+1,...,Aj,使得元素总和最大。

分析:设dp[i]为以i结尾的最大连续和,则d[i] = Max{0,d[i-1]}+Ai;

例题链接:http://acm.hdu.edu.cn/showproblem.php?pid=1003

例题: hdu 1003

Max Sum

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)


Problem Description
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.
 
Input
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).
 
Output
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.
 
Sample Input
2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5
 
Sample Output
Case 1:
14 1 4
 
Case 2:
7 1 6

题意:给n个数,求一个连续子序列的最大和(若有多个,取最左边的一个),并求出最大和的开始节点和终节点。

思路:大致还是上面的思路,只不过多了开始节点和终结点,处理下就可以了

代码:

 1 #include "stdio.h"
 2 #include "string.h"
 3 #define N 100005
 4 #define INF 0x3fffffff
 5 
 6 int a[N];
 7 struct node  //用结构体存,比较方便
 8 {
 9     int l,r;
10     int k;
11 }dp[N];
12 
13 int main()
14 {
15     int T,Case;
16     int n;
17     int i,id;
18     scanf("%d",&T);
19     for(Case=1; Case<=T; Case++)
20     {
21         scanf("%d",&n);
22         for(i=1; i<=n; i++)
23             scanf("%d",&a[i]);
24         for(i=0; i<=n; i++)
25             dp[i].l = dp[i].r = dp[i].k = 0;
26         id = 1;
27         dp[1].l = dp[1].r = 1;
28         dp[1].k = a[1];
29         for(i=2; i<=n; i++)
30         {
31             if(dp[i-1].k >= 0)
32             {
33                 dp[i].k = dp[i-1].k+a[i];
34                 dp[i].l = dp[i-1].l;
35                 dp[i].r = i;
36             }
37             else
38             {
39                 dp[i].k = a[i];
40                 dp[i].l = i;
41                 dp[i].r = i;
42             }
43             if(dp[i].k > dp[id].k)
44                 id = i;
45         }
46         printf("Case %d:
%d %d %d
",Case,dp[id].k,dp[id].l,dp[id].r);
47         if(Case!=T) printf("
");  //格式处理
48     }
49     return 0;
50 }
原文地址:https://www.cnblogs.com/ruo-yu/p/4385264.html