您的位置:首页 > 其它

杭电ACM1003

2016-04-12 15:59 351 查看
Problem Description

Given a sequence a[1],a[2],a[3]……a
, 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

分析:

这个是个动态规划的问题,关于动态规划,简单来说,就是将问题划分为子问题,子问题的解决方法和原问题的解决方法一样。对于这题,就是求n个点的最大子序列和求 n-1个点的最大子序列的方法一样,同理和求n-2,n-3个点的最大子序列的方法一样

import java.util.Scanner;

public class Main8 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int count = 0, a = 0, sum = 0, max;
int j = 0, z, l, r = 0;
for (int i = 1; i <= n; i++) {
count = scanner.nextInt();
sum = 0;
max = -1000;
for (z = l = j = 0; j < count; j++) {
a = scanner.nextInt();
sum += a;
if (max < sum) {
l = z;
r = j;
max = sum;
}
//System.out.println("Debug01--sum-->"+sum+" max-->"+max+" l-->"+l+" r-->"+r+" z-->"+z);
if (sum < 0) {
z = j + 1;
sum = 0;
}
//System.out.println("Debug02--sum-->"+sum+" max-->"+max+" l-->"+l+" r-->"+r+" z-->"+z);
}
System.out.println("Case " + i + ":");
System.out.println(max + " " + (l + 1) + " " + (r + 1));
if (i != n)
System.out.println();
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: