Money exchange issues dynamic planning Print convertible coins all kinds of basic algorithms

Source: Internet
Author: User

There is a monetary system, there are n kinds of coins, the face value of each coin is v1,v2,......, vn, and v1 must be 1, the purpose is to exchange the value of sum money, so that the number of coins is the least.

Result[J] Represents the minimum number of coins with a total value of J,

Print[j] Indicates which coin is used for the value of J.

When there are only 1 kinds of coins, that is, only a coin with a nominal value of 1, the amount of money, the number must be converted. So result[j] = j, j = 0,..., sum


When considering a coin of type I (2,......, N), if the current value is greater than the denomination of the coin, and the total number of coins exchanged with this coin is less than that of the coin, it is exchanged or not exchanged,

The recursive formula is:

result[j] = max{result[j], result[J-v[i]+1]}; Result[J] Big note not convertible coins less, otherwise the exchange of less coins.

The code is as follows

#include <iostream>
#include <vector>
#include <map>
using namespace std;

int main (int argc, char** argv) 
{
	int num,sum;
	Vector<int> v;
	cout<< "Input total amount" <<endl;
	cin>>sum;
	cout<< "type number of coins" <<endl;
	cin>>num;
	cout<< "Enter the face value of each coin separately" <<endl;
	int i=0,j=0,temp;
	for (I=0;i<num;++i)
	{
		cin>>temp;
		V.push_back (temp);
	}
	vector<int> result;
	for (i=0;i<=sum;++i)
		result.push_back (i);
	vector<int> print (sum+1,0);  Output the number of each coin for 
	(i=1;i<num;++i)
	{for
		(j=v[i];j<=sum;++j)
		{
			temp = result[j-v[i]]+1 ;
			if (temp < result[j])
			{
				result[j] = temp;
				PRINT[J] = i;
	}} cout<< "The minimum number of coins for" <<result[sum];
	Map<int,size_t> Map1;
	j = sum;
	while (j>0)
	{
		map1[print[j]]++;
		J-= V[print[j]];
	}
	for (i=0;i<num;++i)
		cout<<endl<< "<<v[i]<<" The number of coins is "<<map1[i];
	return 0;
}


Run results


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.