ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

算法题 背包问题-05-Coins

2020-02-02 15:39:36  阅读:250  来源: 互联网

标签:Coins 05 int coins A1 A3 背包 A2 dp


Whuacmers use coins.They have coins of value A1,A2,A3…An Silverland dollar. One day Hibix opened purse and found there were some coins. He decided to buy a very nice watch in a nearby shop. He wanted to pay the exact price(without change) and he known the price would not more than m.But he didn’t know the exact price of the watch.

You are to write a program which reads n,m,A1,A2,A3…An and C1,C2,C3…Cn corresponding to the number of Tony’s coins of value A1,A2,A3…An then calculate how many prices(form 1 to m) Tony can pay use these coins.
Input
The input contains several test cases. The first line of each test case contains two integers n(1 ≤ n ≤ 100),m(m ≤ 100000).The second line contains 2n integers, denoting A1,A2,A3…An,C1,C2,C3…Cn (1 ≤ Ai ≤ 100000,1 ≤ Ci ≤ 1000). The last test case is followed by two zeros.
Output
For each test case output the answer on a single line.
Sample Input
3 10
1 2 4 2 1 1
2 5
1 4 2 1
0 0
Sample Output
8
4

思路:先输入输入每种硬币的价值,再输入每种硬币的个数求在m以内能组成几种价值

#include<iostream>
#include<stdio.h>
#include<algorithm>
int n, m;
int dp[100001];
int num[105];
int money[105];
using namespace std;
void ZeroOnePack(int w, int v) {
	int j;
	for (j = m; j >= w; j--) {
		dp[j] = max(dp[j], dp[j - w] + v);
	}
}
void CompletePack(int w, int v) {
	int j;
	for (j = w; j <= m; j++) {
		dp[j] = max(dp[j], dp[j - w] + v);
	}
}
void MultiplePack(int w, int v, int amount) {
	if (amount*w >= m) {
		CompletePack(w, v);
		return;
	}
	for (int k = 1; k < amount; k <<= 1) {//用了2进制的思想,2的次方的数字能表达任何数字例如7可以由1+2+4表达
		ZeroOnePack(k*w, k*v);
		amount -= k;
	}
	ZeroOnePack(amount*w, amount*v);
}
int main() {
	while (scanf("%d %d", &n, &m) != EOF) {
		int ans = 0;
		memset(dp, 0, sizeof(dp));
		if (n == 0 && m == 0) {
			break;
		}
		for (int i = 1; i <= n; i++) {
			scanf("%d", &money[i]);
		}
		for (int i = 1; i <= n; i++) {
			scanf("%dd", &num[i]);
		}
		for (int i = 1; i <= n; i++) {
			MultiplePack(money[i], money[i], num[i]);
		}
		for (int i = 1; i <= m; i++) {
			if (dp[i] == i) {
				ans = ans + 1;
			}
		}
		printf("%d\n", ans);
	}
	return 0;
}
实在不知道什么 发布了38 篇原创文章 · 获赞 30 · 访问量 3822 私信 关注

标签:Coins,05,int,coins,A1,A3,背包,A2,dp
来源: https://blog.csdn.net/weixin_43813718/article/details/104145162

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有