[HDOJ] 1003.Max Sum

1003.Max Sum (c++)

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 testcases.
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 
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

题意:求最大子序列和

思路:设置变量max记录最大值,设置下标beg和end记录组成max的元素首与尾。遍历数组,累加求和sum ;如果sum<0时,以当前元素为首元素(t_beg)从新开始,否则继续累加;仅仅当sum>max时,更新beg,end,max。

#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <vector>

#define maxn 100001
using namespace std;
int a[maxn];
int main()
{
  memset(a, 0, sizeof(a));
  int T, Case = 0;
  cin >> T;

  while (T--)
  {
    int n, i;
    cin >> n;
    for (i = 0; i < n; i++)
    {
      int b;
      cin >> b;
      a[i] = b;
    }

    int max = -1001, end = 0, sum = 0, beg = 0, tbeg = 0;
    for (i = 0; i < n; i++)
    {
      sum += a[i];
      if (sum > max)
      {
        max = sum;
        end = i;
        beg = tbeg;
      }
      if (sum < 0)
      {
        sum = 0;
        tbeg = i + 1;
      }
    }
    printf("Case %d:\n", ++Case);
    printf("%d %d %d\n", max, beg + 1, end + 1);
    if (T)
    {
      printf("\n");
    }
  }
  system("pause");
}

猜你喜欢

转载自blog.csdn.net/ruohua3kou/article/details/82109682
今日推荐