A - Max Sum Plus Plus (好题&&dp)

时间:2021-07-08 17:03:44
 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. ^_^

InputEach 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.

OutputOutput 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个子段使其和最大
题解:dp,dp[i][j]表示到a[j]包括a[j]从中去i段的最大值
所以dp[i][j]就分为两种情况:a[j]取或者不取
dp[i%2][k]=max(dp[i%2][k-1],w[k]);
用w[i]记录一定取的情况,又分为两种情况:

1、a[k]作为第i段

2、a[k]加到之前的最大段那里
        w[k]=max(dp[(i-1)%2][k-1],w[k-1])+sum[k]-sum[k-1];

初值:  dp[0][i]               
   if(i==k)dp[i%2][k]=w[k]=sum[k];
具体看代码:
#include<iostream>
#include<string.h>
#include<algorithm>
#include<stdio.h>
#include<queue>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long long ll;
typedef pair<int,int> PII;
#define mod 1000000007
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
//head
#define INF 0x3f3f3f3f
#define N 1000005
int n,m;
int w[N];
int dp[][N];
int sum[N];
int a[N];
int main()
{
ios_base::sync_with_stdio(); cin.tie();
while(cin>>m>>n){
sum[]=;
for(int i=;i<=n;i++)
{
cin>>a[i];
sum[i]=sum[i-]+a[i];
dp[][i]=;
}
for(int i=;i<=m;i++)
{
for(int k=i;k<=n;k++)
{
if(i==k)
dp[i%][k]=w[k]=sum[k];//从k个数中取k段的最大值是前k个数的和
else
{
w[k]=max(dp[(i-)%][k-],w[k-])+sum[k]-sum[k-];//这是一定要取的情况,分为两种:1、a[k]作为第i段,2、a[k]加到之前的最大段那里
dp[i%][k]=max(dp[i%][k-],w[k]);//a[k]取或者不取
}
}
} cout<<dp[m%][n]<<endl;
}
return ; }

参考博客:http://blog.sina.com.cn/s/blog_677a3eb30100jxqa.html

        https://blog.csdn.net/lishuhuakai/article/details/8067474