最大连续和问题,注意其还有一要求是需要路径最长,即:当其和相同时,取路程最大的一段路的起点和终点,也就是说如果其和相同但其路径较短则不必更新先前保存的起点与终点位置。
代码如下:
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<ctime>
using namespace std;
int main()
{
#ifdef test
freopen("in.txt", "r", stdin);
#endif
int t, n, a[20005], ct = 0;
scanf("%d", &t);
while(t--)
{
scanf("%d", &n);
int sum = 0, max = -100000;
int start, end, st = 0;
for(int j = 0; j < n - 1; j++)
{
scanf("%d", &a[j]);
sum = sum + a[j];
if(sum > max)
{
max = sum;
end = j + 1;
start = st;
}
if(sum == max && end - start < j - st) // 和相同时,判断其路径是否比先前的路径长
{
max = sum;
end = j + 1;
start = st;
}
if(sum < 0)
{
sum = 0;
st = j + 1;
}
}
if(max < 0)
printf("Route %d has no nice parts\n", ++ct);
else
printf("The nicest part of route %d is between stops %d and %d\n", ++ct, start + 1, end + 1);
}
return 0;
}