51 Nod 1050 dp

1050 循环数组最大子段和

 
N个整数组成的循环序列a[1],a[2],a[3],…,a[n],求该序列如a[i]+a[i+1]+…+a[j]的连续的子段和的最大值(循环序列是指n个数围成一个圈,因此需要考虑a[n-1],a[n],a[1],a[2]这样的序列)。当所给的整数均为负数时和为0。
例如:-2,11,-4,13,-5,-2,和最大的子段为:11,-4,13。和为20。
 
 

输入

第1行:整数序列的长度N(2 <= N <= 50000)
第2 - N+1行:N个整数 (-10^9 <= S[i] <= 10^9)

输出

输出循环数组的最大子段和。

输入样例

6
-2
11
-4
13
-5
-2

输出样例

20
对于横跨1,n的子段,其实就是总和sum-Min子段和;最后取max即可;
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<string>
#include<cmath>
#include<map>
#include<set>
#include<vector>
#include<queue>
#include<bitset>
#include<ctime>
#include<time.h>
#include<deque>
#include<stack>
#include<functional>
#include<sstream>
//#include<cctype>
//#pragma GCC optimize(2)
using namespace std;
#define maxn 200005
#define inf 0x7fffffff
//#define INF 1e18
#define rdint(x) scanf("%d",&x)
#define rdllt(x) scanf("%lld",&x)
#define rdult(x) scanf("%lu",&x)
#define rdlf(x) scanf("%lf",&x)
#define rdstr(x) scanf("%s",x)
#define mclr(x,a) memset((x),a,sizeof(x))
typedef long long  ll;
typedef unsigned long long ull;
typedef unsigned int U;
#define ms(x) memset((x),0,sizeof(x))
const long long int mod = 1e9 + 7;
#define Mod 1000000000
#define sq(x) (x)*(x)
#define eps 1e-5
typedef pair<int, int> pii;
#define pi acos(-1.0)
//const int N = 1005;
#define REP(i,n) for(int i=0;i<(n);i++)
typedef pair<int, int> pii;

inline int rd() {
	int x = 0;
	char c = getchar();
	bool f = false;
	while (!isdigit(c)) {
		if (c == '-') f = true;
		c = getchar();
	}
	while (isdigit(c)) {
		x = (x << 1) + (x << 3) + (c ^ 48);
		c = getchar();
	}
	return f ? -x : x;
}


ll gcd(ll a, ll b) {
	return b == 0 ? a : gcd(b, a%b);
}
int sqr(int x) { return x * x; }



/*ll ans;
ll exgcd(ll a, ll b, ll &x, ll &y) {
	if (!b) {
		x = 1; y = 0; return a;
	}
	ans = exgcd(b, a%b, x, y);
	ll t = x; x = y; y = t - a / b * y;
	return ans;
}
*/

int n;
int a[maxn];
ll sum = 0;
ll MAX() {
	ll maxx = -inf;
	ll ans = 0;
	for (int i = 1; i <= n; i++) {
		if (ans + 1ll * a[i] > 0) {
			ans += 1ll * a[i];
			maxx = max(maxx, ans);
		}
		else {
			ans = 0;
			maxx = max(maxx, 0ll);
		}
	}
	return maxx;
}



ll MIN() {
	ll minn = inf;
	ll ans = 0;
	for (int i = 1; i <= n; i++) {
		if (ans + 1ll * a[i] < 0) {
			ans += 1ll * a[i];
			minn = min(minn, ans);
		}
		else {
			ans = 0;
			minn = min(minn, 0ll);
		}
	}
	return minn;
}

int main()
{
	//	ios::sync_with_stdio(0);
	n = rd();
	for (int i = 1; i <= n; i++) {
		a[i] = rd(); sum += 1ll * a[i];
	}
	printf("%lld\n", max(MAX(), sum - MIN()));
	return 0;
}

 


posted @ 2019-02-28 09:05  NKDEWSM  阅读(107)  评论(0编辑  收藏  举报