8. Minimum number of coins (dynamic programming)

  1. 8.  Minimum number of coins

[Problem description] This is an old and classic problem. Generally speaking, there are many ways to make up a certain amount of money with several given coins. For example: Given 6 kinds of coins with denominations of 2, 5, 10, 20, 50, and 100, to make up 15 yuan, you can use 5 2 yuan, 1 5 yuan, or 3 5 yuan, or 1 5 yuan 1 yuan, 10 yuan, and so on. Obviously, a minimum of 2 coins is required to make up 15 yuan.
        Your task is, given several different coin denominations, program to calculate the minimum number of coins needed to make up a given amount of money.

【Input form】The input can have multiple test cases. The first line of each test case is the money value M to be pooled (1 <= M<= 2000, integer), and in the next line, the first integer K (1 <= K <= 10) represents the currency number, followed by K different coin denominations Ki (1 <= Ki <= 1000). End when M=0 is entered.

[Output format] Each test case outputs one line, that is, the minimum number of coins required to make up the money value M. If the pool fails, output "Impossible". You can assume that there is an infinite number of each coin to be minted.

【Sample input】

15
6 2 5 10 20 50 100
1
1 2
0

【Sample output】

2
Impossible

Ideas for reference: minimum number of coins (dynamic programming)_enjoy_code_'s blog-CSDN blog_minimum number of coins

#include<bits/stdc++.h>
using namespace std;
int main() {
	int m;//需要凑的钱数
	while(cin>>m&&m) {
		int k;//币种个数
		cin>>k;
		int a[k];//存储所有币种
		int dp[m+1];
		//dp[i]表示凑i元时需要的最小钱币数
		//将dp进行初始化,因为要找最少钱币数,所以将之初始化为比较大的值

		for(int i=0; i<m+1; i++) {
			dp[i]=INT_MAX/10;//这里稍微小一点,避免越界出现错误
		}

		//初始化边界条件:
		dp[0]=0;//凑齐0元最少需要0张钱币

		for(int i=0; i<k; i++) {
			cin>>a[i];
		}
		sort(a,a+k);//将币种升序排列

		//寻找状态转移方程:dp[i]=min(dp[i-a[j]]+1,dp[i]),
		//dp[i]中的i表示需要凑的钱数,a[j]表示已知的钱币数
		for(int i=1; i<m+1; i++) {//i表示需要凑的钱币数

			for(int j=0; j<k; j++) {//j是所有币种在a中的下标

				if(a[j]>i)
					break;
				else {
					dp[i]=min(dp[i-a[j]]+1,dp[i]);//考虑选择要不要当前币种
				}
			}
		}
		
		if(dp[m]!=INT_MAX/10)
			cout<<dp[m]<<endl;
		else
			cout<<"Impossible"<<endl;
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/longzaizai_/article/details/120301988
Recommended