题意:给出一个由正数和负数组成的数组,求其最大子数组和,要求如果子数组和相等,选择最长的子数组组成的
思路:f[i] = max{f[i] + a[i], a[i]},同时记录起始位置和终止位置,当存在相等情况时,选择终止位置与起始位置之差最大的
代码如下:
#include <cstdio>
#include <climits>
using namespace std;
const int N = 20001;
int s, cas;
int route[N];
void input();
void solve();
int main()
{
#ifndef ONLINE_JUDGE
freopen("f:\\OJ\\uva_in.txt", "r", stdin);
#endif
int b;
scanf("%d", &b);
while (b--)
{
input();
solve();
}
return 0;
}
void input()
{
scanf("%d", &s);
for (int i = 0; i < s - 1; i++)
{
scanf("%d", &route[i]);
}
}
void solve()
{
int sum = INT_MIN / 2;
int f = sum;
int start = 0, stop = 0;
int temp_start = 0;
for (int i = 0; i < s - 1; i++)
{
if (f < 0)
{
temp_start = i + 1;
f = route[i];
}
else
{
f += route[i];
}
if (f >= sum)
{
if (f > sum)
{
start = temp_start;
stop = i + 2;
}
else if (i + 2 - temp_start > stop - start)
{
start = temp_start;
stop = i + 2;
}
sum = f;
}
}
if (sum > 0)
{
printf("The nicest part of route %d is between stops %d and %d\n", ++cas, start, stop);
}
else
{
printf("Route %d has no nice parts\n", ++cas);
}
}