Max Sum HDU - 1003

   Given a sequence a11 ,a22 ,a33 ......ann , 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.
InputThe 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).
   OutputFor 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.动规:dp[i]=max(dp[i-1]+a[i],a[i]),dp[i]表示以i为末尾的连续序列的最大和。
2.非动规:请看代码~~~参考了大神的代码,我还是太弱了,orz!!!
 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstdio>
 4 using namespace std;
 5 
 6 int n,m;
 7 int a[100005];
 8 
 9 int main()
10 {   cin>>n;
11     for(int t=1;t<=n;t++){
12         scanf("%d",&m);
13         for(int i=1;i<=m;i++) scanf("%d",&a[i]);
14         
15         int sum=0,maxsum=-10000,l=1,r=1,temp=1;
16         for(int i=1;i<=m;i++){
17             sum+=a[i];
18             if(sum>maxsum){
19                 maxsum=sum;
20                 l=temp;
21                 r=i;
22             }
23             if(sum<0){
24                 sum=0;
25                 temp=i+1;
26             }
27         }
28         printf("Case %d:\n%d %d %d\n",t,maxsum,l,r);
29         if(t!=n) printf("\n");
30     }
31 } 

 

posted @ 2017-05-04 23:00  天之道,利而不害  阅读(205)  评论(0编辑  收藏  举报