题目要求
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.
给定由n个整数(可能为负数)组成的序列{a1,a2,…,an},以及一个正整数m,要求确定序列{a1,a2,…,an}的m个不相交子段,使这m个子段的总和达到最大。
题目链接
http://acm.hdu.edu.cn/showproblem.php?pid=1024
题解
设
d
p
[
i
]
[
j
]
dp[i][j]
dp[i][j]是前i个数,必须算上i,分为j段的最大和。现在i可能与前面的连成一段,也可以与前面的不算一段。这样转移方程就是
d
p
[
i
]
[
j
]
=
m
a
x
(
d
p
[
i
−
1
]
[
j
]
,
d
p
[
k
]
[
j
−
1
]
)
+
a
[
i
]
,
1
≤
k
≤
i
−
1
dp[i][j]=max(dp[i-1][j],dp[k][j-1])+a[i],1\le k \le i-1
dp[i][j]=max(dp[i−1][j],dp[k][j−1])+a[i],1≤k≤i−1
这个一看就能滚动数组优化的。第一重循环肯定是枚举j的,这样能记录上一轮的dp的前缀最大值。滚动数组记录上一轮的前缀最大值,本轮完了就用本轮的dp值更新滚动数组。
时间复杂度无论如何都是O(nm),空间复杂度优化到O(n)。
AC代码
import java.util.*;
public class Main {
static final int NN=1000100;
static final long oo=1000000000000000000l;
static int[] a=new int[NN];
static long[] dp=new long[NN];
static long[] maxdp=new long[NN];
public static void main(String[] args) throws Exception {
Scanner sc=new Scanner(System.in);
while(sc.hasNextInt()){
int m=sc.nextInt(),n=sc.nextInt();
for(int i=1;i<=n;i++){
a[i]=sc.nextInt();
}
long ans=-oo;
for(int i=0;i<=n;i++)maxdp[i]=0;
for(int i=0;i<=n;i++)dp[i]=0;
for(int j=1;j<=m;j++){
dp[0]=-oo;
for(int i=1;i<=n;i++){
dp[i]=Math.max(dp[i-1],maxdp[i-1])+a[i];
}
maxdp[0]=-oo;
for(int i=1;i<=n;i++){
maxdp[i]=Math.max(maxdp[i-1],dp[i]);
}
}
for(int i=1;i<=n;i++)ans=Math.max(ans,dp[i]);
System.out.println(ans);
}
sc.close();
}
}
探讨了在给定整数序列中寻找m个不相交子段使其总和最大的问题,通过动态规划方法实现,介绍了状态转移方程及滚动数组优化技巧。
227

被折叠的 条评论
为什么被折叠?



