ps:题目有坑,我开25*105的数组就段错误,莫名贡献一次RE,这个dp应该不难(懒得滚动数组了)
dp[i][j]
表示用前i个物品凑出j的最小邮票数目,那么他的转移方程是,用前i-1个物品凑出j的邮票数目,和用前i个物品凑出j-a[i]的邮票数目+1的最小值
d p [ i ] [ j ] = m i n ( d p [ i − 1 ] [ j ] , d p [ i − 1 ] [ j − a [ i ] ] + 1 ) dp[i][j]=min(dp[i-1][j],dp[i-1][j-a[i]]+1) dp[i][j]=min(dp[i−1][j],dp[i−1][j−a[i]]+1)
值得注意的是,这种题如果给每种硬币加一个数量也是类似的解法,即使数量很大我们也可以通过三重循环加剪枝来解决。这类问题统称为部分和问题
下面是两道poj的例题题解,及时复习
#include<iostream>
#include<string>
#include<string.h>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<map>
#include<queue>
using namespace std;
#define ll int
#define MAX 250
#define inf 10000000
ll a[MAX], n, m, dp[MAX][1005];
int main() {
while (cin >> m >> n) {
for (int i = 0; i <= n; i++)for (int j = 1; j <= m; j++)dp[i][j] = inf;
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (j < a[i]) dp[i][j] = dp[i - 1][j];
else dp[i][j] = min(dp[i - 1][j], dp[i - 1][j - a[i]] + 1);
}
}
if (dp[n][m] != inf)cout << dp[n][m] << endl;
else cout << 0 << endl;
}
}