题意:有N堆石子排成一排,每堆石子有一定的数量。现要将N堆石子并成为一堆。合并的过程只能每次将相邻的两堆石子堆成一堆,每次合并花费的代价为这两堆石子的和,经过N-1次合并后成为一堆。求出总的代价最小值。
分析:动态规划
状态定义:dp[i[[j] = 把第i堆到第j堆并成一堆时的最优解(最少代价)
状态转移方程:dp[i][j] = dp[i][k] + dp[k+1][j] + sum;(sum为当前代价,即i堆到j堆的和)
代码:
#include<bits/stdc++.h> using namespace std; const int N = 205; const int INF = 1000000000; int dp[N][N]; int sum[N]; int main() { int n; while(scanf("%d", &n) != EOF) { int w; sum[0] = 0; for(int i = 1; i <= n; i++) { scanf("%d", &w); sum[i] = sum[i-1] + w; } for(int i = 0; i <= n; i++) fill(dp[i], dp[i] + N, INF); for(int i = 1; i <= n; i++) dp[i][i] = 0; for(int i = 2; i <= n; i++) { for(int j = 1; j <= n - i + 1; j++) { int e = i + j - 1; for(int k = j; k < e; k++) { dp[j][e] = min(dp[j][e], dp[j][k] + dp[k+1][e]); } dp[j][e] += sum[e] - sum[j-1]; } } printf("%d ", dp[1][n]); } return 0; }