hdu 1003 Max Sum (DP)

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

Max Sum

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 158421    Accepted Submission(s): 37055


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
 
题目大意:给一串数字,然后要求出和最大的连续子序列。并且题目要求这个和最大的连续子序列输出起始位置和终止位置。
注意:初始化问题,还有空格的这个格式问题!
 
详见代码。
 1 #include <iostream>
 2 #include <cstdio>
 3 
 4 using namespace std;
 5 
 6 struct node
 7 {
 8     int s,e,smax;
 9 } sum[100010];
10 
11 int main ()
12 {
13     int t,n,Max,k,j;
14     int num[100010];
15     while (~scanf("%d",&t))
16     {
17         int flag=1;
18         while (t--)
19         {
20 
21             scanf("%d",&n);
22             for (int i=0; i<n; i++)
23             {
24                 scanf("%d",&num[i]);
25             }
26             sum[0].smax=num[0];
27             sum[0].s=sum[0].e=0;
28             k=0,j=0;
29             Max=sum[0].smax;
30             for (int i=1; i<n; i++)
31             {
32                 if (num[i]>sum[i-1].smax+num[i])
33                 {
34                     sum[i].smax=num[i];
35                     sum[i].s=i;
36                     sum[i].e=i;
37                 }
38                 else
39                 {
40                     sum[i].smax=sum[i-1].smax+num[i];
41                     sum[i].s=sum[i-1].s;
42                     sum[i].e=i;
43                 }
44                 if (Max<sum[i].smax)
45                 {
46                     Max=sum[i].smax;
47                     k=sum[i].s;
48                     j=sum[i].e;
49                 }
50             }
51             printf ("Case %d:
",flag++);
52             printf ("%d %d %d
",Max,k+1,j+1);
53             if (t)
54                 printf ("
");
55         }
56     }
57     return 0;
58 }
 
 
原文地址:https://www.cnblogs.com/qq-star/p/4269531.html