题意:
In a galaxy far away, the planet Equator is under attack! The evil gang Galatic Criminal People Cooperation is planning robberies in Equator’s cities. Your help is needed! In order to complete your training for becoming a lord of the dark side you should help them deciding which cities to rob.
As the name says, the desert planet Equator only can be inhabited on its equator. So the gang lands there at some point and travels into some direction robbing all cities on their way until leaving the planet again.
But what is still open for them is to decide where to land, which direction to take, and when toleave. Maybe they shouldn’t even enter the planet at all? They do not consider costs for travelingor for running their ship, those are peanuts compared to the money made by robbery!
The cities differ in value: some are richer, some are poorer, some have better safety functions. So the gang assigned expected profits or losses to the cities. Help them deciding where to begin and where to end their robbery to maximize the money in total when robbing every city in between.
输入
The input starts with the number of test cases T ≤ 30. Each test case starts a new line containingthe number of cities 1 ≤ n ≤ 1 000 000. In the same line n integers c i follow. Each c i (0 ≤ i < n,−1000 ≤ c i ≤ +1000) describes the money obtained when robbing city i, a negative c i describes the amount of money they would lose.
输出
For each test case print one integer describing the maximum money they can make in total.
样例输入
3
3 1 2 3
8 4 5 -1 -1 1 -1 -1 5
2 -1 -1
样例输出
6
14
0
这道题翻译成中文的意思大概就是给出一个n个数围成一圈,问最大连续自序列的和是多少?
思路:
这道题解法有很多,自己习惯用尺取来求解。对于一个循环的序列,它的最大连续自序列要么是在这个数组中连续,要么是在这个数组中首尾相连。对于在这个数组中连续,我们可以通过尺取法求出来。对于收尾相连,我们可以换位思考,求出数组中连续的最小连续子序列,那么用数组的权值和减去最小连续子序列,剩下的两段连接起来就是收尾相连的最大连续子序列,我们只需要比较数组中连续的和数组首尾相连,取最大值即是正确答案
代码:
#include <stdio.h>
#include <algorithm>
#define ll long long
using namespace std;
ll a[1000005];
int main () {
int T, n;
scanf("%d", &T);
while(T --) {
ll sum = 0;
ll maxx = 0;
ll minn = 0x3f3f3f3f;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%lld", &a[i]);
sum += a[i];
}
int endd = 0;
ll num = 0;
while(endd < n) {
if (num + a[endd] < 0) {
num = 0;
} else {
num += a[endd];
maxx = max(num, maxx);
}
endd ++;
}
num = 0; endd = 0;
while(endd < n) {
if (num + a[endd] > 0) {
num = 0;
} else {
num += a[endd];
minn = min(num, minn);
}
endd ++;
}
ll ans = max(maxx, sum - minn);
printf("%lld\n", ans);
}
return 0;
}
转载请注明出处!!!
如果有写的不对或者不全面的地方 可通过主页的联系方式进行指正,谢谢