题目:
2 5 6 -1 5 4 -7 7 0 6 -1 1 -6 7 -5
Case 1: 14 1 4 Case 2: 7 1 6
求最大连续子段和,并求其起止位置。
解题思路:
本身求最大连续子段和不难。
需要在每一步都与当前最大和进行比较,然后记录其起止位置。
源代码:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n,m,i,dp[100005],max2,num[100005],maxl,maxr;//用max2记录最大子段和
cin >> n;
for (int t = 1; t <= n; t++)
{
cin >> m;
memset(dp,0,sizeof(dp));
memset(num,0,sizeof(num));
dp[0] = 0;
max2 = -999999999;//因为可能均为负数,所以max2设置最小值
int flag = 1;
for (i = 1; i <= m; i++)
{
cin >> num[i];
dp[i] = dp[i - 1] + num[i];
if (dp[i] > max2)//比较过程中判断,并更新其起止位置。
{
max2 = dp[i];
maxl = flag;
maxr = i;
}
if (dp[i] < 0)
{
dp[i] = 0;
flag = i + 1;
}
}
cout << "Case " << t << ":" << endl << max2 << " " << maxl << " " << maxr << endl;
if (t != n)
cout << endl;
}
return 0;
}