51nod-1021 石子归并

基准时间限制:1 秒 空间限制:131072 KB 分值: 20  难度:3级算法题
 收藏
 关注
N堆石子摆成一条线。现要将石子有次序地合并成一堆。规定每次只能选相邻的2堆石子合并成新的一堆,并将新的一堆石子数记为该次合并的代价。计算将N堆石子合并成一堆的最小代价。

例如: 1 2 3 4,有不少合并方法
1 2 3 4 => 3 3 4(3) => 6 4(9) => 10(19)
1 2 3 4 => 1 5 4(5) => 1 9(14) => 10(24)
1 2 3 4 => 1 2 7(7) => 3 7(10) => 10(20)

括号里面为总代价可以看出,第一种方法的代价最低,现在给出n堆石子的数量,计算最小合并代价。
Input
第1行:N(2 <= N <= 100)
第2 - N + 1:N堆石子的数量(1 <= A[i] <= 10000)
Output
输出最小合并代价
Input示例
4
1
2
3
4
Output示例
19

题解:定义dp[i][j]为将[i, j]石子合并的最小代价,则dp[i][j] = min (dp[i][k] + dp[k + 1][j] + i ~ j 区间和, dp[i][j]);注意是以j - i递增,因为大区间的获得需要小区间为前提

AC代码

#include <stdio.h>
#include <iostream>
#include <string>
#include <queue>
#include <map>
#include <vector>
#include <algorithm>
#include <string.h>
#include <cmath>
typedef long long ll;

using namespace std;

const ll maxn = 111, inf = 1e18 + 10;
ll a[maxn], ans;

ll dp[maxn][maxn], sum[maxn];

int main(){
	ll n;
	scanf("%lld", &n);
	sum[0] = 0;
	for(ll i = 0; i < n; i++){
		scanf("%lld", &a[i]), sum[i] = (i == 0 ? a[i] : sum[i - 1] + a[i]); 
	}
	for(int i = 0; i < n; i++){
		for(int j = 0; j < n; j++)
			dp[i][j] = inf;
		dp[i][i] = 0;
	}
	ans = 1e18;
	for(ll len = 1; len < n; len++){
		for(ll i = 0; i + len < n; i++){
			for(ll k = i; k < i + len; k++){
				dp[i][i + len] = min(dp[i][i + len], dp[i][k] + dp[k + 1][i + len] + sum[i + len] - (i == 0 ? 0 : sum[i - 1]));
			}
		}
	}
	printf("%lld\n", dp[0][n - 1]);
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/qq_37064135/article/details/80010982