J - Max Sum

J - Max Sum

Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u

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

//第一行代表有 t 组测试案例,问最大连续的和为多少,并输出第几位数到第几位数
//虽然,这是一道dp水题,但我从没做过,自己写出来感觉不错,62ms 比别人的慢了一倍,应该是我用了两次一重循环吧。

 1 #include <stdio.h>
 2 
 3 #define MAXN 100005
 4 
 5 int num[MAXN];
 6 int dp[MAXN];
 7 
 8 int cmp(int a,int b)
 9 {
10     return a>b?a:b;
11 }
12 
13 int main()
14 {
15     int t;
16     int n,i,Case=0;
17     scanf("%d",&t);
18     while (t--)
19     {    
20         scanf("%d",&n);
21         int max;
22         for (i=1;i<=n;i++)
23         {
24             if (i==1)
25             {
26                 scanf("%d",&num[i]);
27                 dp[i]=num[i];
28                 max=i;
29                 continue;
30             }
31             scanf("%d",&num[i]);
32             dp[i]=cmp(num[i],dp[i-1]+num[i]);
33             if (dp[i]>dp[max]) max=i;
34         }
35         int s=max;
36         for (i=max;i>=1;i--)
37         {
38             if (dp[i]>=0)
39                 s=i;
40             if (dp[i]<0)
41                 break;
42         }
43         printf("Case %d:\n",++Case);
44         printf("%d %d %d\n",dp[max],s,max);
45         if (t!=0) printf("\n");
46     }
47     return 0;
48 }
View Code

 

 
posted @ 2016-08-08 15:46  happy_codes  阅读(126)  评论(0编辑  收藏  举报