题目:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1050
题意:给定一个长度为50000的数组,求它的循环数组的最大子段和。
分析:本题与普通的最大子段和问题不同的是,最大子段和可以是首尾相接的情况,即可以循环。那么这个题目的最
大子段和有两种情况
(1)正常数组中间的某一段和最大。这个可以通过普通的最大子段和问题求出。
(2)此数组首尾相接的某一段和最大。这种情况是由于数组中间某段和为负值,且绝对值很大导致的,那么我
们只需要把中间的和为负值且绝对值最大的这一段序列求出,用总的和减去它就行了。
即,先对原数组求最大子段和,得到ans1,然后把数组中所有元素符号取反,再求最大子段和,得到ans2,
原数组的所有元素和为ans,那么最终答案就是
max(ans1, ans + ans2)。
代码:
#include <iostream> #include <string.h> #include <stdio.h> using namespace std; typedef long long LL; const int N = 50005; int a[N]; LL Work(int a[], int n) { LL ans = 0; LL tmp = 0; for(int i=0; i<n; i++) { if(tmp < 0) tmp = a[i]; else tmp += a[i]; ans = max(ans, tmp); } return ans; } int main() { int n; while(scanf("%d", &n)!=EOF) { LL ans = 0; for(int i=0; i<n; i++) { scanf("%d", &a[i]); ans += a[i]; } LL ans1 = Work(a, n); for(int i=0; i<n; i++) a[i] = -a[i]; LL ans2 = Work(a, n); ans = max(ans + ans2, ans1); printf("%I64d\n", ans); } return 0; }