hdu1003-Max Sum

Max Sum

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


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
 

这道题与“最大连续子序列和”类似,所以还是用类似的dp思想。

只是最大连续子序列和多了一个注:【注】:为方便起见,如果所有整数均为负数,则最大子序列和为0。

在讨论里找的多几组测试数据

4 0 0 2 0 —— 2 1 3
6 2 7 -9 5 4 3 —— 12 1 6
4 0 0 -1 0 —— 0 1 1
7 -1 -2 -3 -2 -5 -1 -2 —— -1 1 1
6 -1 -2 -3 1 2 3 —— 6 4 6
----------------------------------------------------------------------------------
增加一组测试数据:
5 -3 -2 -1 -2 -3 —— -1 3 3

 

 1 #include <iostream>
 2 #include <cstring>
 3 #include <algorithm>
 4 
 5 using namespace std;
 6 
 7 #define INF 0x3f3f3f3f
 8 #define MAXN 100010
 9 
10 int main()
11 {
12     int T;
13     cin >>T;
14     int i, j;
15     int a;
16     for(i = 1;i <= T;++i)
17     {
18 //      可以推断出当 t > 0 时可由 t += a 计算出最大值(就像最大连续子序列和)
19 //      当 t < 0 时,按照dp思想,dp[i] = max(dp[i-1] + a[i], a[i])
20 //      所以分两种情况,t < a 时,t = a;
21 //            
22 //      t > a 时,t += a(这并不影响最大值ans,例如-1,-2,ans已经存了-1)
23 //      为什么要 +=a?是为了保证子序列的连续,直到出现 t < a
24         int n;
25         cin >>n>>a;
26         int t = a, l = 1, r = 1;
27         int ans = a, num_start = 1, num_end = 1;
28         for(j = 2;j <= n;++j)
29         {
30             cin >>a;  
31             if(t < 0 && t < a)
32             {
33                 t = a;
34                 l = r = j;
35             }
36             else
37             {
38                 t += a;
39                 r++;
40             }
41             if(ans < t)
42             {
43                 ans = t;
44                 num_start = l;
45                 num_end = r;
46             }
47         }
48         cout <<"Case "<<i<<":"<<endl
49             <<ans<<" "<<num_start<<" "<<num_end<<endl;
50         if(i != T)
51             cout <<endl;
52     }
53     return 0;
54 }

 

posted @ 2018-04-10 20:48  谁知道你啊啊啊  阅读(141)  评论(0编辑  收藏  举报