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. ^_^
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.
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
题意:增强版最大子序列,题意,把一段序列分成很多段,找其中的m段组成最大和。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).
就是互不相交的意思。。
。。第一次做dp的题,用滚动的数组和状态dp得到每个子序列的最优解,然后一步步影响总体,得到总体的最优解。
然而因为数的个数太大 有100万,所以二维肯定不行,得用一维。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#define MAXN 1000000
#define INF 0x7fffffff //0x7个f代表最大的数加了负号得到最小数
int dp[MAXN+10];
int mmax[MAXN+10];
int a[MAXN+10];
using namespace std;
int main()
{
int n,m;
while(cin>>m>>n)
{
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
mmax[i]=0;
dp[i]=0;
}
int mmmax;
dp[0]=0;
mmax[0]=0;
for(int i=1;i<=m;i++)
{
//分成m个子序列,求每个子序列的情况最优,每次求得子序列的最优,第二次的最优是建立在第一次的最优上面
mmmax=-INF;
for(int j=i;j<=n;j++)
{
dp[j]=max(dp[j-1]+a[j],mmax[j-1]+a[j]);
//dp代表的是把当前数加到上一个组里面,mmax是把a[j]单独放一个组里面,
//由于在mmax里面 a[j]是一个单独的数的存在,能影响他的只有前j-1子序列的最优的状态
//所以下面更新的mmax是更新j-1而不是j,避免在同一个子序列状态被同一个子序列影响
//而且下面的作用是为了得到当前子序列的的每个位置的最优解来影响下一个序列得到整体的最优解。
//而dp是为了得到当前序列(在前面最优解影响的情况下得到的最优解)。
mmax[j-1]=mmmax;
mmmax=max(mmmax,dp[j]);
}
}
cout<<mmmax<<endl;
}
}