有n堆石子排成一列,每堆石子有一个重量w[i], 每次合并可以合并相邻的两堆石子,一次合并的代价为两堆石子的重量和w[i]+w[i+1]。问安排怎样的合并顺序,能够使得总合并代价达到最小。
第一行一个整数n(n<=100)
第二行n个整数w1,w2...wn (wi <= 100)
一个整数表示最小合并代价
4
4 1 1 4
18
#include<stdio.h> #include<algorithm> using namespace std; int a[105]; int sum[105]; int d[105][105]; const int INF = (1 << 30); int main(){ int n, i; scanf("%d", &n); for (i = 1; i <= n; i++){ scanf("%d", &a[i]); sum[i] = sum[i - 1] + a[i]; } int len, j, k; for (len = 1; len < n; len++){ for (i = 1; i <= n - len; i++){ int res = INF; j = i + len; for (k = i; k < j; k++) res = min(res, d[i][k] + d[k + 1][j] + sum[j] - sum[i - 1]); d[i][j] = res; } } printf("%d\n", d[1][n]); return 0; }
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; int a[110]; int sum[110]; int dp[110][110]; const int INF = (1 << 30); int solve(int l, int r) { if (dp[l][r] != -1) return dp[l][r]; int res = INF; for (int i = l; i <= r - 1; i++) res = min(res, solve(l, i) + solve(i + 1, r) + sum[r] - sum[l - 1]); return dp[l][r] = res; } int main() { int n; scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); sum[i] = sum[i - 1] + a[i]; } memset(dp, -1, sizeof(dp)); for (int i = 1; i <= n; i++) //注意要初始化为0 dp[i][i] = 0; printf("%d\n", solve(1, n)); return 0; }
原文地址:http://blog.csdn.net/u013174702/article/details/43985083