换零钱, 计算有多少方案数
#include <stdio.h> #include <string.h> #include <algorithm> using namespace std; #define N 100010 int dp[N], w[5], v[5], n, m; int main() { w[0] = 1; w[1] = 5; w[2] = 10; w[3] = 25; w[4] = 50; memset(dp, 0, sizeof(dp)); dp[0] = 1; for(int i = 0; i < 5; i++) { for(int j = w[i]; j <= 7800; j++) { dp[j] = dp[j] + dp[j - w[i]]; } } while(~scanf("%d", &n)) { printf("%d\n", dp[n]); } return 0; }
这个是 求最小的 方案,而以前做的都是求最大
#include <stdio.h> #include <string.h> #include <algorithm> using namespace std; #define N 100010 int dp[N], w[N], v[N], n, m; int main() { int t; scanf("%d", &t); while(t--) { int x, y, z; scanf("%d %d", &x, &y); z = y - x; scanf("%d", &n); for(int i = 0; i < n; i++) { scanf("%d %d", &v[i], &w[i]); } for(int i = 0;i <= z; i++) dp[i] = 9999999; dp[0] = 0; for(int i = 0; i < n; i++) { for(int j = w[i]; j <= z; j++) { dp[j] = min(dp[j], dp[j - w[i]] + v[i]); } } if(dp[z] == 9999999 ) printf("This is impossible.\n"); else printf("The minimum amount of money in the piggy-bank is %d.\n", dp[z]); } return 0; }
典型的分组背包,每个course 是一组, 注意三层循环的次序问题
#include <stdio.h> #include <string.h> #include <algorithm> using namespace std; #define N 200 int dp[N], w[N][N], n, m; int main() { while(~scanf("%d %d", &n, &m)) { if(m + n == 0) break; memset(w, 0, sizeof(w)); for(int i = 1; i <= n; i++) { for(int j = 1; j <= m; j++) scanf("%d", &w[i][j]); } memset(dp, 0, sizeof(dp)); for(int i = 1; i <= n; i++) { for(int j = m; j >= 0; j--) { for(int k = 0; k <= j; k++) dp[j] = max(dp[j], dp[j - k] + w[i][k]); //printf("dp[%d][%d] = %d\n", i, j, dp[j]); } } printf("%d\n", dp[m]); } return 0; }