`

UVA Let Me Count The Ways(357)

 
阅读更多

题目大意:

       US 的硬币工分为以下五种:penny: 1c, nickel: 5c, dime: 10c, quarter: 25c, half-dollar: 50c,若Mel去商店里买东西,店家找他 N cents,问使用上面5种penny,共有几种找法?即有几种方法能够凑出N cents?

其中0 <= N <= 30000;

 

解题思路:

       完全背包问题,解决方法就是将N从 1 到 30000 中,每个N有几种凑成方法都算一遍。

      状态转移方程: dp[j] += dp[ j - coin[i] ];    即如果j - coin[i] 能够由coin[i]凑成的话,那么 j 也能由coin[i]凑成,凑成的方法总数就为当前的总量加上 j - coin[i] 的总量。注意,dp的类型要为long long 类型,int的类型不够,会溢出的。(我刚开始没注意,一直错。。。囧!)

 

代码:

#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;

long long dp[30010]={0};  
int coin[5] = {1,5,10,25,50};

int main()
{
	long long sum;
	dp[0] = 1;
	for( int i = 0; i < 5; i++ )
	{
		for( int j = coin[i]; j <= 30000; j++ )
		{
			if( dp[ j - coin[i] ] )
				dp[j] += dp[ j - coin[i] ];
		}
	}

	freopen( "test.txt", "r", stdin );
	freopen( "test.out", "w", stdout );
	while( cin>>sum )
	{
		if( dp[sum] == 1 )
		{
			cout<<"There is only 1 way to produce "<<sum<<" cents change."<<endl;
			continue;
		}		
		cout<<"There are "<<dp[sum]<<" ways to produce "<<sum<<" cents change."<<endl; 
	}

	return 0;
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics