杭电oj-1003(Max Sum)

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

本题求解的是最大子段问题,也就是说从任何一个数开始,连续的中间不能间断,几个数都可以,把这些数加在一起求出最大值,然后返回这个最大值,并且返回初始下标和终止的下标。

这道题原本是笔者数据结构课上的一道题,我当初做出来的时候,那个高兴啊,没想到在acm里原来是道水题,O(∩_∩)O哈哈哈~,这道题采用暴力求解,分治算法都是可以解决的,当然最好的思想还是动态规划的做法,时间负责度仅为O(n),在一次循环中动态更新最大值和起始下标与终止下标就可以实现啦。

代码:


import java.util.Scanner;

public class Main1003 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int T, N, num, startP = 1, endP = 1;
        T = in.nextInt();
        int m = T;
        while (T-- > 0) {
            int max = -1001, temp = 1, sum = 0;
            N = in.nextInt();
            for (int i = 1; i <= N; i++) {
                num = in.nextInt();
                sum += num;
                if (sum > max) {
                    max = sum;
                    startP = temp;
                    endP = i;
                }
                if (sum < 0) {
                    sum = 0;
                    temp = i + 1;
                }
            }
            System.out.println("Case " + (m - T) + ":");
            System.out.println(max + " " + startP + " " + endP);
            if (T != 0) {
                System.out.println("");
            }
        }
    }
}

你可能感兴趣的:(杭电oj-1003(Max Sum))