Uva 11450 Wedding Shopping

本文详细解析了UVA 11450问题,该问题类似于01背包问题,通过使用动态规划(DP)解决在限购额下能否买到所有种类物品的问题。文章提供了完整的C++代码实现,阐述了状态转移方程及算法流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:https://uva.onlinejudge.org/external/114/11450.pdf

分析:此题与01背包问题有些相似,因为能买的东西的最大价格取决于限购额M和要买东西的种类,可以用dp[i][j]来代表在购买种类为j的情况下,可不可能剩下i数量的钱数。如果dp[k][n] (M \geq k \geq 0) 为true的话,则最终答案为 max(M - k)。反之,若dp[k][n]都是false,则代表在限购额M的情况下不可能把所有物品都买齐,则输出Impossible。

状态转移方程为:dp[i][j] = dp[i][j] \ || \ dp[i - 1][j + cost[k]], k \ is \ the \ an \ item \ under \ category \ i

#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");
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值