设a[1-n]为输入的数组,DP[i]表示以i位置结尾最大的子段和,当DP[i-1]大于等于0时表示DP[i-1]对a[i]有贡献则DP[i]=DP[i-1]+a[i]否则DP[i]=a[i],这里代码中省略了a数组。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <string>
#include <string.h>
#include <cmath>
#include <sstream>
#include <set>
#include <map>
#include <functional>
#include <queue>
#include <vector>
using namespace std;
const int maxn = 100010;
int arr[maxn], dp[maxn];
int t, n, a, res;
int main()
{
cin >> t;
int num = t;
int Case = 0;
while (t--)
{
int Max, start, lst, fst, n;
lst = fst = start = 1;
cin >> n;
for (int i = 1; i <= n; i++)
cin >> dp[i];
Max = dp[1];
for (int i = 2; i <= n; i++)
{
if (dp[i - 1] >= 0)
{
dp[i] = dp[i - 1] + dp[i];
}
else
start = i;
if (dp[i] > Max)
{
fst = start;
lst = i;
Max = dp[i];
}
}
cout << "Case " << ++Case << ":\n";
cout << Max << " " << fst << " " << lst << ((Case == num) ? "\n" : "\n\n");
}
}