Description
Now I think you have got an AC in Ignatius.L's "Max Sum" problem. To be a brave ACMer, we always challenge ourselves to more difficult problems. Now you are faced with a more difficult problem.
Given a consecutive number sequence S 1, S 2, S 3, S 4 ... S x, ... S n (1 ≤ x ≤ n ≤ 1,000,000, -32768 ≤ S x ≤ 32767). We define a function sum(i, j) = S i + ... + S j (1 ≤ i ≤ j ≤ n).
Now given an integer m (m > 0), your task is to find m pairs of i and j which make sum(i 1, j 1) + sum(i 2, j 2) + sum(i 3, j 3) + ... + sum(i m, j m) maximal (i x ≤ i y ≤ j x or i x ≤ j y ≤ j x is not allowed).
But I`m lazy, I don't want to write a special-judge module, so you don't have to output m pairs of i and j, just output the maximal summation of sum(i x, j x)(1 ≤ x ≤ m) instead. ^_^
Given a consecutive number sequence S 1, S 2, S 3, S 4 ... S x, ... S n (1 ≤ x ≤ n ≤ 1,000,000, -32768 ≤ S x ≤ 32767). We define a function sum(i, j) = S i + ... + S j (1 ≤ i ≤ j ≤ n).
Now given an integer m (m > 0), your task is to find m pairs of i and j which make sum(i 1, j 1) + sum(i 2, j 2) + sum(i 3, j 3) + ... + sum(i m, j m) maximal (i x ≤ i y ≤ j x or i x ≤ j y ≤ j x is not allowed).
But I`m lazy, I don't want to write a special-judge module, so you don't have to output m pairs of i and j, just output the maximal summation of sum(i x, j x)(1 ≤ x ≤ m) instead. ^_^
Input
Each test case will begin with two integers m and n, followed by n integers S
1, S
2, S
3 ... S
n.
Process to the end of file.
Process to the end of file.
Output
Output the maximal summation described above in one line.
Sample Input
1 3 1 2 3 2 6 -1 4 -2 3 -2 3
Sample Output
6 8
Hint
Huge input, scanf and dynamic programming is recommended.
/* 題意:給你一個長度為n的序列,讓你求出最大m個字段的序列元素和 初步思路:動態規划最大m字段和,dp數組,dp[i][j]表示以a[j]結尾的,i個字段的最大和 兩種情況:1.第a[j]元素單獨作為第i個字段 2.第a[j]元素和前面的字段共同當做第i個字段 得到狀態轉移方程:dp[i][j]=max( dp[i][j-1]+a[j] , max(dp[i-1][t])+a[j]); 但是實際情況是,時間復雜度和空間復雜度都是相當的高,所以要進行時間和空間的優化: 將每次遍歷的時候的max(dp[i-1][t]) 用一個數組d儲存起來,這樣就能省去尋找max(dp[i-1][t])的時間, 這樣狀態轉移方程就變成了 dp[i][j]=max( dp[i][j-1]+a[j] , d[j-1]+a[j]), 會發現dp數組的可以 省去一維,因為每次都是和前一次的狀態有關,所以可以記錄前一次狀態,再用一個變量tmp記錄下dp[i][j-1], 這樣方程就變成了 dp[i][j]=max( tmp+a[j] , d[j-1]+a[j]);這樣就可以化簡一下就是:dp[i][j]= max( tmp , d[j-1])+a[j]; */ #include <bits/stdc++.h> #define N 1000005 using namespace std; int a[N]; int n,m; int d[N];//用來存儲j-1的位置用來存儲 max(dp[i-1][t]) int main(){ // freopen("in.txt","r",stdin); while(scanf("%d%d",&m,&n)!=EOF){ memset(d,0,sizeof d); for(int i=1;i<=n;i++){ scanf("%d",&a[i]); } /* dp[i][j]=max( dp[i][j-1]+a[j] , max(dp[i-1][t])+a[j]) */ for(int i=1;i<=m;i++){//遍歷字段 int tmp = 0;//用來記錄dp[i-1][j] for(int k = 1; k <= i; ++k) tmp += a[k]; //由於d[n]的位置是永遠都用不到的,所以就用來存儲最后的姐 d[n] = tmp;//前面的i項,每項都是一個段的時候 for(int j = i+1; j <= n; ++j) { tmp = max(d[j-1], tmp) + a[j]; //a[j]單獨作為一個段的情況 和 前面的max(dp[i-1][t]) d[j-1] = d[n];//將這個值保存下來 d[n] = max(d[n], tmp); //比較大小方便答案的輸出 } } printf("%d\n",d[n]); } return 0; }