NYOJ737 -- Combination of stones (1)
Stone Merge (a) time limit: 1000 MS | memory limit: 65535 KB difficulty: 3
There are N piles of stones in a row, and each pile of stones has a certain number. Now we want to build N piles of stones into a pile. The merge process can only pile the adjacent two piles of stones into a pile each time, the cost of each merge is the sum of the two piles of stones, after the N-1 merge into a pile. Obtain the minimum total cost.
Multiple groups of test data are input, and the input ends with the end of the file.
The first line of each group of test data has an integer n, indicating that there are n piles of stones.
The next row contains n (0 <n <200) numbers, indicating the number of these n heaps respectively. The minimum output cost is separated by spaces, which accounts for a single row of sample input.
31 2 3713 7 8 16 21 4 18
Sample output
9239
Source
Classic Problems
Interval dp, where dp [I] [j] indicates the minimum cost of merging the j heap stones from the I heap stones, then dp [I] [j] = min (dp [I] [k] + dp [k + 1] [j] + sum [I] [j])
#include #include
#include
#include
#include
#include
#include
#include
#include
#include
#include using namespace std;const int N = 220;const int inf = 0x3f3f3f3f; int w[N];int dp[N][N];int sum[N];int main(){int n;while (~scanf("%d", &n)){sum[0] = 0;for (int i = 1; i <= n; i++){scanf("%d", &w[i]);sum[i] = sum[i - 1] + w[i];}memset (dp, 0, sizeof(dp));for (int i = n; i >= 1; i--){for (int j = i + 1; j <= n; j++){int tmp = inf;for (int k = i; k < j; k++){tmp = min(tmp, dp[i][k] + dp[k + 1][j] + sum[j] - sum[i - 1]);}dp[i][j] = tmp;}}printf("%d\n", dp[1][n]);}return 0;}