对应NYOJ题目:点击打开链接
3 1 2 3 7 13 7 8 16 21 4 18
9
思路:区间DP,dp[i][j] 表示合并第i个石子到第j个石子最少需要花费的总代价。
O O O | O O O O
比如最后一次合并是左三个跟右四个合并,那转移方程为:
dp[i][j] = min{dp[i][j], dp[i][k] + dp[k+1][j] + sum[i][j]};
其中 i <= k <= j;sum[i][j] 表示第i个到第j个石子间的总和,其在转移方程的意义是左边跟右边合并需要的代价,因为不管k在哪,左右合并都是需要sum[i][j]的代价。
也可以转化为记忆化搜索来理解;
DP:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <algorithm> #define M 210 const int INF = (1<<30); #define MIN(x, y) ((x)<(y) ? (x):(y)) using namespace std; int sum[M]; int dp[M][M]; int main() { //freopen("in.txt", "r", stdin); int n; int i, j, k, len, val; while(~scanf("%d", &n)) { memset(sum, 0, sizeof(sum)); for(i=0; i<M; i++) for(j=0; j<M; j++) dp[i][j] = INF; for(i=1; i<=n; i++){ scanf("%d", &val); sum[i] = sum[i-1] + val; dp[i][i] = 0; } for(len=2; len<=n; len++){ for(i=1; i+len-1<=n; i++){ j = i + len - 1; for(k=i; k+1<=j; k++){ dp[i][j] = MIN(dp[i][j], dp[i][k] + dp[k+1][j] + sum[j] - sum[i-1]); } } } printf("%d\n", dp[1][n]); } return 0; }
记忆化搜索:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <algorithm> #define M 210 const int INF = (1<<30); #define MIN(x, y) ((x)<(y) ? (x):(y)) using namespace std; int sum[M]; int dp[M][M]; int Dfs(int l, int r) { if(l == r) return 0; if(dp[l][r] != INF) return dp[l][r]; int k, ans = INF; for(k=l; k+1<=r; k++) ans = MIN(ans, Dfs(l, k) + Dfs(k+1, r) + sum[r] - sum[l-1]); dp[l][r] = ans; return ans; } int main() { //freopen("in.txt", "r", stdin); int n; int i, j, k, len, val; while(~scanf("%d", &n)) { memset(sum, 0, sizeof(sum)); for(i=1; i<=n; i++) for(j=1; j<=n; j++) dp[i][j] = INF; for(i=1; i<=n; i++){ scanf("%d", &val); sum[i] = sum[i-1] + val; } printf("%d\n", Dfs(1, n)); } return 0; }