HDUOJ----1003 Max Sum

Max Sum

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

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

Author

Ignatius.L

http://acm.hdu.edu.cn/showproblem.php?pid=1003

动态规划....求最大子段和;

代吗:

 1 #include<iostream>
 2 #include<vector>
 3 using namespace std;
 4 int main()
 5 {
 6     int t,n,i,k,st,en,maxn,sum,flag=1;
 7     cin>>t;
 8     while(t--)
 9     {
10         cin>>n;
11         vector<int>arr(n);
12         for(i=0;i<n;i++)
13             cin>>arr[i];
14           st=en=sum=0;
15         for(i=0,k=0;i<n;i++)
16          {
17             sum+=arr[i];
18             if(i==0||sum>maxn)
19            {
20                 maxn=sum;
21                 en=i;
22                 st=k;
23            } 
24           if(sum<0)
25            {
26              sum=0;
27              k=i+1;
28            }
29          }
30          cout<<"Case "<<flag++<<":"<<endl;
31          cout<<maxn<<" "<<st+1<<" "<<en+1<<endl;
32          if(t!=0)cout<<endl;
33     }
34     return 0;
35 }

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

扫码关注云+社区

领取腾讯云代金券