题目链接:https://uva.onlinejudge.org/external/114/11450.pdf
分析:此题与01背包问题有些相似,因为能买的东西的最大价格取决于限购额M和要买东西的种类,可以用dp[i][j]来代表在购买种类为j的情况下,可不可能剩下i数量的钱数。如果dp[k][n] () 为true的话,则最终答案为 max(M - k)。反之,若dp[k][n]都是false,则代表在限购额M的情况下不可能把所有物品都买齐,则输出Impossible。
状态转移方程为:
#include <cstdio>
#include <vector>
#include <string>
#include <cstring>
using namespace std;
const int maxn = 200 + 5;
const int maxc = 20 + 5;
bool dp[maxc][maxn];
vector<int> cost[maxc];
int main() {
int n;
scanf("%d", &n);
while (n--) {
memset(dp, 0, sizeof(dp));
for (int i = 0; i < maxc; i++) cost[i].clear();
int M, g;
scanf("%d%d", &M, &g);
for (int i = 1; i <= g; i++) {
int j;
scanf("%d", &j);
for (int k = 0; k < j; k++) {
int temp;
scanf("%d", &temp);
cost[i].push_back(temp);
}
}
dp[0][M] = true;
for (int i = 1; i <= g; i++) {
for (int j = 0; j <= M; j++) {
for (int k = 0; k < cost[i].size(); k++) {
if (j + cost[i][k] <= M) dp[i][j] = dp[i][j] || dp[i - 1][j + cost[i][k]];
}
}
}
bool flag = false;
for (int i = 0; i <= M; i++)
if (dp[g][i] == true) {
flag = true;
printf("%d\n", M - i);
break;
}
if (!flag) printf("%s\n", "no solution");
}
}