钱币兑换问题
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 7270 Accepted Submission(s): 4272
Problem Description
在一个国家仅有1分,2分,3分硬币,将钱N兑换成硬币有很多种兑法。请你编程序计算出共有多少种兑法。
Input
每行只有一个正整数N,N小于32768。
Output
对应每个输入,输出兑换方法数。
Sample Input
2934 12553
Sample Output
718831 13137761
有三种币值的硬币 1分 2分 3分 将n兑换成硬币有几种兑换方式
可以得到一个母函数a(x)=(1+x+x^2+……)(1+x^2+x^4+……)(1+x^3+x^6+……)
n的值相对比较大 需要预处理出所有的答案才不会tle
#include <cstdio>
#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <string.h>
#include <string>
#include <vector>
#include <queue>
#define MEM(a,x) memset(a,x,sizeof a)
#define eps 1e-8
#define MOD 10009
#define MAXN 33000
#define MAXM 100010
#define INF 99999999
#define ll __int64
#define bug cout<<"here"<<endl
#define fread freopen("ceshi.txt","r",stdin)
#define fwrite freopen("out.txt","w",stdout)
using namespace std;
int Read()
{
char c = getchar();
while (c < '0' || c > '9') c = getchar();
int x = 0;
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = getchar();
}
return x;
}
void Print(int a)
{
if(a>9)
Print(a/10);
putchar(a%10+'0');
}
int a[MAXN],b[MAXN];
void init()
{
for(int i=0;i<=32768;i++)
{
a[i]=1;
b[i]=0;
}
for(int i=2;i<=3;i++)
{
for(int j=0;j<=32768;j++)
for(int k=0;k+j<=32768;k+=i)
{
b[j+k]+=a[j];
}
for(int j=0;j<=32768;j++)
{
a[j]=b[j];
b[j]=0;
}
}
}
int main()
{
//fread;
init();
int n;
while(scanf("%d",&n)!=EOF)
{
printf("%d\n",a[n]);
}
return 0;
}
完全背包解法:
#include <cstdio>
#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <string.h>
#include <string>
#include <vector>
#include <queue>
#define MEM(a,x) memset(a,x,sizeof a)
#define eps 1e-8
#define MOD 10009
#define MAXN 330010
#define MAXM 100010
#define INF 99999999
#define ll __int64
#define bug cout<<"here"<<endl
#define fread freopen("ceshi.txt","r",stdin)
#define fwrite freopen("out.txt","w",stdout)
using namespace std;
int Read()
{
char c = getchar();
while (c < '0' || c > '9') c = getchar();
int x = 0;
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = getchar();
}
return x;
}
void Print(int a)
{
if(a>9)
Print(a/10);
putchar(a%10+'0');
}
int dp[MAXN];
int main()
{
//fread;
int n;
int val[3]={1,2,3};
while(scanf("%d",&n)!=EOF)
{
MEM(dp,0);
dp[0]=1;
for(int i=0;i<3;i++)
{
for(int j=val[i];j<=n;j++)
{
dp[j]+=dp[j-val[i]];
}
}
printf("%d\n",dp[n]);
}
return 0;
}