題目連接:http://acm.hdu.edu.cn/showproblem.php?pid=1024
題意 求 M 段 不相交 的 字段的和的最大值 。
經典的動態規劃
用 fk][j] 表示 選擇 了 K 段 在 1到 j 內選擇的最大值
狀態轉移方程爲: f[k][j] = max{ f[k][j-1]+a[j] , max( f[k-1][t] + a[j] ) }
import java.util.Scanner;
public class HDU1024 {
/*
* 動態轉轉移方程
* f[k][j] // 表示共 1……j 物品, 選取 k段的 最大值
* f[k][j] = max{f[k][j-1] + a[j], max{ f[k-1][t] + a[j]} t ∈ 1……j-1}}
* (1) 當a[j] 物品是在 第 k 段中時候 f[k][j] = f[k][j-1]+ a[j]
* (2) 當 j 單獨的作爲 第 K 段 那麼 爲 第 k-1 段中最大的 + a[j] 即可 max{ f[k-1][t] k-1<t<j-1 }
* 應爲 f[k][] 只由 f[k-1][] 決定 所以 可以 用滾動數組實現
*/
private int n,m;
static private int inf = (-1)*1<<30;
private int a[] ;
private int f[];//
private int pre[];
int max;
public void solve(){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
m = sc.nextInt();
n = sc.nextInt();
a = new int[n+1]; f = new int[n+1];pre = new int[n+1];
for(int i=1;i<=n;i++){
a[i] = sc.nextInt();
}
//初始化
f[0] = 0; pre[0] = inf;
for(int i=1;i<=m;i++){
max = inf;
for( int j=i;j<=n;j++){
f[j] = f[j-1]>pre[j-1]?f[j-1]+a[j]:pre[j-1]+a[j];
pre[j-1] = max;
if( f[j] > max){
max = f[j];
}
}
}
System.out.println(max);
}
}
public static void main(String[] args) {
new HDU1024().solve();
}
}