HDU-2069 Coin Change (DP / 暴力枚举)

这篇博客介绍了如何使用动态规划和暴力枚举两种方法解决硬币找零问题。动态规划解决方案通过创建二维数组dp来记录不同金额下的找零方式数,而暴力枚举则通过遍历所有可能的硬币组合进行计数。文章提供了两种方法的C++代码实现,并给出了样例输入和输出。

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

Coin Change

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 34020    Accepted Submission(s): 12225


 
Problem Description
Suppose there are 5 types of coins: 50-cent, 25-cent, 10-cent, 5-cent, and 1-cent. We want to make changes with these coins for a given amount of money.

For example, if we have 11 cents, then we can make changes with one 10-cent coin and one 1-cent coin, or two 5-cent coins and one 1-cent coin, or one 5-cent coin and six 1-cent coins, or eleven 1-cent coins. So there are four ways of making changes for 11 cents with the above coins. Note that we count that there is one way of making change for zero cent.

Write a program to find the total number of different ways of making changes for any amount of money in cents. Your program should be able to handle up to 100 coins.
 
Input
The input file contains any number of lines, each one consisting of a number ( ≤250 ) for the amount of money in cents.
 
Output
For each input line, output a line containing the number of different ways of making changes with the above 5 types of coins.
 
Sample Input
 
  
11 26
 
Sample Output
 
  
4 13
 
Author
Lily
 
Source
 
Recommend
linle
 

Statistic | Submit | Discuss | Note

Home | TopHangzhou Dianzi University Online Judge 3.0
Copyright © 2005-2021 HDU ACM Team. All Rights Reserved.
Designer & Developer : Wang Rongtao LinLe GaoJie GanLu
Total 0.000000(s) query 1, Server time : 2021-07-28 18:48:47, Gzip enabled
Administration

第一种做法DP 

#include<iostream>
#define ll long long 
using namespace std;
int dp[251][101];
int type[5]={1,5,10,25,50};
void solve()
{
	dp[0][0]=1;
	for(int i=0;i<5;i++)//5种类型的面值 
	{
		for(int j=1;j<101;j++)//硬币的个数 
		{
			for(int k=type[i];k<251;k++)
			{
				dp[k][j]+=dp[k-type[i]][j-1];
			}
		} 
	}
}
int main()
{
	int ans[251]={0};
	solve();
	for(int i=0;i<251;i++)//0元~251元 
	{
		for(int j=0;j<101;j++)//0个硬币~100个硬币
		{
			ans[i]+=dp[i][j];
		} 
	}
	int s;
	while(cin>>s)
	{
		cout<<ans[s]<<endl;
	} 
	return 0;
}

 第二种:暴力枚举

#include<iostream>
using namespace std;
int main()
{
	int x,ans;
	while(cin>>x)
	{
		ans=0;
		int a,b,c,d,e;
		
		for(a=0;a<=x;a++)
		{
			for(b=0;b*5<=x-a;b++)
			{
				for(c=0;c*10<=x-a-b*5;c++)
				{
					for(d=0;d*25<=x-a-b*5-c*10;d++)
					{
						e=x-a-5*b-10*c-25*d;
						
					    if(e%50==0&&a+b+c+d+e/50<=100)//e是个整数 且硬币个数在100个以内 
						ans++;
						
					}
				}
			}
		}
		cout<<ans<<endl;
	}
	return 0;
 } 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值