HDU 1024:Max Sum Plus Plus(DP)
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 39886 Accepted Submission(s): 14338
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 . We define a function .
Now given an integer , your task is to find m pairs of i and j which make maximal ( or 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 and , just output the maximal summation of instead.
Input
Each test case will begin with two integers and , followed by integers .
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方程无论是在时间上还是在空间上都是不允许的。
那么我们就需要对这个方程进行优化:
不难发现当前状态只与两个状态有关:
- 第个数和前个数在一段里
- 第个数和前个数不在一段里。
根据这一点,我们把状态降成一维的数组,表示前个数分段时的最大和,然后用来表示状态一的前个数在前段的最大和,表示状态二的前个数在前段的最大和。
当前状态的转移方程为:,持续更新dp与sum数组的值
AC代码
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <limits.h>
#include <map>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <string>
#include <time.h>
#define ll long long
#define ull unsigned long long
#define ms(a,b) memset(a,b,sizeof(a))
#define pi acos(-1.0)
#define INF 0x7f7f7f7f
#define lson o<<1
#define rson o<<1|1
#define bug cout<<"-------------"<<endl
#define debug(...) cerr<<"["<<#__VA_ARGS__":"<<(__VA_ARGS__)<<"]"<<"\n"
const double E=exp(1);
const int maxn=1e6+10;
const int mod=1e9+7;
using namespace std;
int a[maxn];
int dp[maxn];
int sum[maxn];
int main(int argc, char const *argv[])
{
ios::sync_with_stdio(false);
cin.tie(0);
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
double _begin_time = clock();
#endif
int k,n;
while(cin>>k>>n)
{
int res;
for(int i=1;i<=n;i++)
cin>>a[i];
ms(dp,0);
ms(sum,0);
for(int i=1;i<=k;i++)
{
res=-INF;
for(int j=i;j<=n;j++)
{
dp[j]=max(sum[j-1],dp[j-1])+a[j];
sum[j-1]=res;
res=max(res,dp[j]);
}
}
cout<<res<<endl;
}
#ifndef ONLINE_JUDGE
long _end_time = clock();
printf("time = %lf ms.", _end_time - _begin_time);
#endif
return 0;
}