1. 程式人生 > >hdu 1024 Max Sum Plus Plus(m段最大和)

hdu 1024 Max Sum Plus Plus(m段最大和)

inf col ati ace NPU cme out cout long

Problem 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 S1, S2, S3, S4 ... Sx, ... Sn (1 ≤ x ≤ n ≤ 1,000,000, -32768 ≤ Sx
≤ 32767). We define a function sum(i, j) = Si + ... + Sj (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(i1, j1) + sum(i2, j2) + sum(i3, j3) + ... + sum(im, jm) maximal (ix ≤ iy ≤ jx or ix ≤ jy ≤ jx 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(ix
, jx)(1 ≤ x ≤ m) instead. ^_^

Input Each test case will begin with two integers m and n, followed by n integers S1, S2, S3 ... Sn.
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 思路: 狀態dp[i][j] 有前j個數,組成i組的和的最大值。 決策: 第j個數,是在第包含在第i組裏面,還是自己獨立成組。 方程 dp[i][j]=Max(dp[i][j-1]+a[j] , max( dp[i-1][k] ) + a[j] ) 0<k<j 空間復雜度,m未知,n<=1000000, 繼續滾動數組。 時間復雜度 n^3. n<=1000000. 顯然會超時,繼續優化。 max( dp[i-1][k] ) 就是上一組 0....j-1 的最大值。我們可以在每次計算dp[i][j]的時候記錄下前j個 的最大值 用數組保存下來 下次計算的時候可以用,這樣時間復雜度為 n^2.
#include <cstdio>
#include 
<map> #include <iostream> #include<cstring> #include<bits/stdc++.h> #define ll long long int #define M 6 using namespace std; inline ll gcd(ll a,ll b){return b?gcd(b,a%b):a;} inline ll lcm(ll a,ll b){return a/gcd(a,b)*b;} int moth[13]={0,31,28,31,30,31,30,31,31,30,31,30,31}; int dir[4][2]={1,0 ,0,1 ,-1,0 ,0,-1}; int dirs[8][2]={1,0 ,0,1 ,-1,0 ,0,-1, -1,-1 ,-1,1 ,1,-1 ,1,1}; const int inf=0x3f3f3f3f; const ll mod=1e9+7; int m,n; int a[1000007]; int dp1[1000007]; int dp2[1000007]; int main(){ //ios::sync_with_stdio(false); while(~scanf("%d%d",&m,&n)){ memset(dp1,0,sizeof(dp1)); memset(dp2,0,sizeof(dp2)); for(int i=1;i<=n;i++) scanf("%d",&a[i]); int maxn; for(int i=1;i<=m;i++){ //枚舉子序列 maxn=-inf; for(int j=i;j<=n;j++){ //j = i是因為每個子序列最少1個元素 dp1[j]=max(dp2[j-1]+a[j],dp1[j-1]+a[j]); dp2[j-1]=maxn; maxn=max(maxn,dp1[j]); } } cout<<maxn<<endl; } }

hdu 1024 Max Sum Plus Plus(m段最大和)