标签:
第1行:2个数N和M,中间用空格分隔。N为整数的个数,M为划分为多少段。(2 <= N , M <= 5000) 第2 - N+1行:N个整数 (-10^9 <= a[i] <= 10^9)
输出这个最大和
7 2 -2 11 -4 13 -5 6 -2
26
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <limits.h> using namespace std; typedef long long LL; #define MAXN 5010 const LL MIN_INF = -(1 << 30); LL dp[MAXN], input[MAXN], pre[MAXN]; int n, m; int main() { scanf("%d%d", &n, &m); dp[0] = MIN_INF; pre[0] = 0; for(int i = 1; i <= n; i++) { scanf("%I64d", &input[i]); pre[i] = 0; dp[i] = MIN_INF; } LL ans = MIN_INF; while(m--) { ans = MIN_INF; for(int i = 1; i <= n; i++) { if(i == 1) dp[i] = pre[i - 1] + input[i]; else { if(dp[i - 1] > pre[i - 1]) { dp[i] = dp[i - 1] + input[i];//第i个数与它的上一个数在同一子段内 } else { dp[i] = pre[i - 1] + input[i];//从第i个分出一个新的子段 } } //dp[i] = max(dp[i - 1], pre[i - 1]) + input[i]; 或者直接这么取值也可 pre[i - 1] = ans; ans = max(ans, dp[i]); } pre[n] = ans; } printf("%I64d\n", pre[n]); return 0; }
51nod 1052最大M子段和 & poj 2479最大两子段和
标签:
原文地址:http://www.cnblogs.com/gaoxiang36999/p/4665495.html