钱币兑换问题

来源:互联网 发布:站长工具域名ip查询 编辑:程序博客网 时间:2024/04/30 08:27

钱币兑换问题

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 3653    Accepted Submission(s): 2059


Problem Description
在一个国家仅有1分,2分,3分硬币,将钱N兑换成硬币有很多种兑法。请你编程序计算出共有多少种兑法。
 

Input
每行只有一个正整数N,N小于32768。
 

Output
对应每个输入,输出兑换方法数。
 

Sample Input
293412553
 

Sample Output
71883113137761
 

Author
SmallBeer(CML)
 

Source
杭电ACM集训队训练赛(VII)
解法1:母函数

#include<iostream>
using namespace std;
#define n 32770
int main()
{

 
  int a[32770],b[32770],i,j,k;
  for(i=0;i<=n;i++)
  {
   a[i]=1;
   b[i]=0;
  }
  for(i=2;i<=3;i++)
  {
   for( j=0;j<=n;j++)
   {
    for( k=0;k+j<=n;k+=i)
     b[j+k]+=a[j];
   }
   for(j=0;j<=n;j++)
   {
    a[j]=b[j];
    b[j]=0;
   }
   
  }
  int N;
  while(cin>>N){
  cout<<a[N]<<endl;
 }
 return 0;
}

 
解法2:完全背包
 
#include<iostream>
using namespace std;
int main()
{
 int n;
 int i,j;
 int dp[32769];
 memset(dp,0,sizeof(dp));
 dp[0]=1;
 for(i=1;i<=3;i++)
  for(j=i;j<=32769;j++)
   dp[j]+=dp[j-i];
  while(cin>>n)
  {
   
   cout<<dp[n]<<endl;
   
  }
  return 0;
}
 
数学方法:
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
int N;
int main()
{
    while(~scanf("%d", &N))
    {
        int s = N/3+1;
        for(int i = 0 ; i <= N/3 ; i++)
        {
            int t = (N-3*i)/2;
            s += t;
        }
        printf("%d\n", s);
    }
    return 0;
}
原创粉丝点击