Jill likes to ride her bicycle, but since the pretty city of Greenhills where she lives has grown, Jill often uses the excellent public bus system for part of her journey. She has a folding bicycle which she carries with her when she uses the bus for the first part of her trip. When the bus reaches some pleasant part of the city, Jill gets off and rides her bicycle. She follows the bus route until she reaches her destination or she comes to a part of the city she does not like. In the latter event she will board the bus to finish her trip.
Through years of experience, Jill has rated each road on an integer scale of ``niceness.‘‘ Positive niceness values indicate roads Jill likes; negative values are used for roads she does not like. There are not zero values. Jill plans where to leave the bus
and start bicycling, as well as where to stop bicycling and re-join the bus, so that the sum of niceness values of the roads she bicycles on is maximized. This means that she will sometimes cycle along a road she does not like, provided that it joins up two
other parts of her journey involving roads she likes enough to compensate. It may be that no part of the route is suitable for cycling so that Jill takes the bus for its entire route. Conversely, it may be that the whole route is so nice Jill will not use
the bus at all.
Since there are many different bus routes, each with several stops at which Jill could leave or enter the bus, she feels that a computer program could help her identify the best part to cycle for each bus route.
The nicest part of route r is between stops i and
j
However, if the maximal sum is not positive, your program should print:
Route r has no nice parts
3 3 -1 6 10 4 -5 4 -3 4 4 -4 4 -5 4 -2 -3 -4
The nicest part of route 1 is between stops 2 and 3 The nicest part of route 2 is between stops 3 and 9 Route 3 has no nice parts
题目大意:每组样例包括两个部分:1)点的个数n
2)n-1 个点与点间的值
求最长最大连续和。
潜力:往后加还有没有可能获取更大的值。
#include<stdio.h> #include<string.h> #include<stdlib.h> #include<algorithm> using namespace std; int num[20005], n, L, R, l, r; int cal() { int sum = 0, temp = 0; l = r = 0; for (int i = 1; i < n; i++) { temp += num[i]; if (temp < 0) { temp = 0; l = i; } else if (temp > sum || (temp == sum && l == L - 1)) { //相等时必须要左边界相等,才成立 sum = temp; L = l + 1; R = i + 1; } } return sum; } int main() { int T, Case = 1; scanf("%d", &T); while (T--) { scanf("%d", &n); memset(num, 0, sizeof(num)); L = R = l = r = 0; for (int i = 1; i < n; i++) { scanf("%d", &num[i]); } int ans = cal(); if (!ans) { printf("Route %d has no nice parts\n", Case++); } else { printf("The nicest part of route %d is between stops %d and %d\n", Case++, L, R); } } return 0; }
原文地址:http://blog.csdn.net/llx523113241/article/details/44044867