给出n个数,求其m个子段和的最大值。
动态规划问题
#include <cstdio> #include <cstring> #include <algorithm> #define INF 0x7fffffff #define N 1000000+5 using namespace std; int now[N];//包含a[j]的最大值 int lstmax[N];//前j个的可以不包含a[j]的最大值 int a[N];//储存输入的数字 int mmax;//每一轮的最大值 int main() { int m, n; freopen("C:\Users\super\Documents\CB_codes\in.txt", "r", stdin); while( ~ scanf("%d%d", &m, &n)) { for(int i = 1; i <= n; i ++) { scanf("%d", &a[i]); } now[0] = 0; memset(lstmax, 0, sizeof(lstmax) ); for(int i = 1; i <= m; i ++) { mmax = -INF; for(int j = i; j <= n; j ++) { now[j] = max(now[j-1] + a[j], lstmax[j-1] + a[j] );//包含a[j]的最大值 lstmax[j-1] = mmax;//上一轮的最大值,j-1 mmax = max(mmax, now[j]);//这一轮的最大值,j } } printf("%d ", mmax); } fclose(stdin); return 0; }