hdu2069Coin Change 暴力/背包/母函数

Coin Change

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


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
 


做法一:暴力

#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;


int main()
{
	int i,j,k,l;
	int n,t;
	while(scanf("%d",&n)!=EOF)
	{
		t=0;
		for(int i=0;i*50<=n;i++)
		for(int j=0;j*25<=n;j++)
		for(int k=0;k*10<=n;k++)
		for(int l=0;l*5<=n;l++)
		if(n-i*50-j*25-k*10-l*5>=0&&i+j+k+l+n-i*50-j*25-k*10-l*5<=100)
		t++;
		printf("%d\n",t);
	 } 
 	return 0;
}

做法二:完全背包

#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
int n,dp[110][300];
int money[5]={1,5,10,25,50};

int main()
{
	int n;
	while(scanf("%d",&n)!=EOF)
	{
		memset(dp,0,sizeof(dp));
		dp[0][0]=1;//规定是金额为0的方案为1个 
		for(int i=0;i<5;i++)
			for(int j=1;j<=100;j++)
				for(int k=n;k>=money[i];k--)
					dp[j][k]+=dp[j-1][k-money[i]];
		int ans=0;
		for(int i=0;i<=100;i++)
		ans+=dp[i][n];
		printf("%d\n",ans);
	} 
 	return 0;
}


做法三:母函数

#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
const int N=300; 
int c1[N][110],c2[N][110];
int res[N],money[6]={0,1,5,10,25,50};

void Init()
{
	memset(c1,0,sizeof(c1));
	memset(c2,0,sizeof(c2));
	c1[0][0]=1;
	for(int i=1;i<=5;i++)
	{
		for(int j=0;j<=250;j++)
		{
			for(int k=0;j+k*money[i]<=250;k++)
			{
				for(int p=0;k+p<=100;p++)  //限制硬币的总数不超过100 
				c2[j+k*money[i]][p+k]+=c1[j][p];
			}
		}
		for(int j=0;j<=250;j++)
		{
			for(int p=0;p<=100;p++) 
			{
				c1[j][p]=c2[j][p];
				c2[j][p]=0;
			}
		}
	}
	for(int i=1;i<=250;i++)
		for(int j=0;j<=100;j++)
			res[i]+=c1[i][j];
	res[0]=1;
}

int main()
{
	int n;
	Init();
	while(~scanf("%d",&n))
	{
		printf("%d\n",res[n]);
	}
 	return 0;
}


猜你喜欢

转载自blog.csdn.net/cao2219600/article/details/80016114