AcWing 282. [Java] 石子合并
原题链接
简单
作者:
Aranne
,
2020-07-08 12:21:19
,
所有人可见
,
阅读 481
import java.util.*;
class Main {
Scanner sc = new Scanner(System.in);
int maxn = 305;
int n;
int[] stones = new int[maxn];
int[] pre = new int[maxn];
int[][] dp = new int[maxn][maxn];
void run() {
n = sc.nextInt();
for (int i = 0; i < n; i++) {
stones[i] = sc.nextInt();
}
for (int i = 1; i <= n; i++) {
pre[i] = pre[i - 1] + stones[i - 1];
}
for (int len = 2; len <= n; len++) {
for (int i = 0, j = len - 1; j < n; i++, j++) {
int min = Integer.MAX_VALUE;
for (int k = i; k < j; k++) {
min = Math.min(min, dp[i][k] + dp[k + 1][j] + pre[j + 1] - pre[i]);
}
dp[i][j] = min;
}
}
System.out.println(dp[0][n - 1]);
}
public static void main(String[] args) {
Main m = new Main();
m.run();
}
}