问题描述:
People in Silverland use square coins. Not only they have square shapes but also their values are square numbers. Coins with values of all square numbers up to 289 (=17^2), i.e., 1-credit coins, 4-credit coins, 9-credit coins, ..., and 289-credit coins, are available in Silverland.
There are four combinations of coins to pay ten credits:
ten 1-credit coins,
one 4-credit coin and six 1-credit coins,
two 4-credit coins and two 1-credit coins, and
one 9-credit coin and one 1-credit coin.
Your mission is to count the number of ways to pay a given amount using coins of Silverland.
输入:
The input consists of lines each containing an integer meaning an amount to be paid, followed by a line containing a zero. You may assume that all the amounts are positive and less than 300
输出:
For each of the given amount, one line containing a single integer representing the number of combinations of coins should be output. No other characters should appear in the output.
案例分析:
常见的万能模板:
#include<iostream>
using namespace std;
const int _max=1001;
int main()
{
int i,j,k,n;
int c1[_max],c2[_max];
while(cin>>n && n!=0)
{
for(i=0;i<=n;i++)
//n代表从1克到n克砝码,c1初始化完成把质量从0到n的所有砝码都初始化为1
{
c1[i]=1;
c2[i]=0;//中间存放数据的数组
}
//这里的i代表从第二个表达式开始计算,j代表前面计算的表达式的第j个变量
for(i=2;i<=n;i++)
{
for(j=0;j<=n;j++)
{
//k代表的是第二个表达式里各项系数,而且注意到k每次增加i
for(k=0;k+j<=n;k+=i)
{
c2[j+k]+=c1[j];// 这里要注意一下依照的系数是j的不是k的
//意思是c1[j]是前面累乘的系数,而k是后面式子的
}
}
//重新把c1、c2初始化
for(j=0;j<=n;j++)
{
c1[j]=c2[j];
c2[j]=0;
}
}
for(i=0;i<n;i++)
{
cout<<c1[i]<<endl;
}
}
return 0;
}
hdu 1398代码及分析:
//HDOJ_1398 Square Coins
#include<iostream>
using namespace std;
//1、这里要注意的一个问题是_max=301,若取300,acm上会出现wrong answer
const int _max=301;
int main()
{
int c1[_max],c2[_max];
int i,j,k,n;
//这里的n代表想求的硬币的币值
while(cin>>n && n!=0)
{
for(i=0;i<=n;i++)
{
c1[i]=1;
c2[i]=0;
}
//i表示是从第二个式子开始一直到第n个式子,j表示前面累乘的式子的第j项
//k表示第i个式子里第k项,注意一下对于第i个式子里k每次增加i的平方
for(i=2;i<=n;i++)
{
for(j=0;j<=n;j++)
{
for(k=0;j+k<=n;k+=i*i)
{
//2、注意这里相加的是c1[j],而不是c1[k],因为前者表示累乘的系数,这样才对
c2[j+k]+=c1[j];
}
}
for(j=0;j<=n;j++)
{
c1[j]=c2[j];
c2[j]=0;
}
}
cout<<c1[n]<<endl;
}
return 0;
}
hdu 1398代码稍微做了一些变化
#include <iostream>
using namespace std;
const int _max=301;
int c1[_max],c2[_max];
//这里引进了数组 这个代码可以
int dir[17]={1,4,9,16,25,36,49,64,81,100,121,144,169,196,225,256,289};
int main()
{ int n,i,j,k;
while (cin>>n && n!=0)
{
for (i=2;i<=17;i++)
{
for (j=0;j<=n;j++)
//这里刚才出错地方是数组a的范围小,代入i时越界了
for (k=0;k+j<=n;k+=dir[i-1])
{
c2[j+k]+=c1[j];
}
for (j=0;j<=n;j++)
{
c1[j]=c2[j];
c2[j]=0;
}
}
cout<<c1[n]<<endl;
}
return 0;
}
这里有一个小问题,就是dir数组初始化时,利用for循环,则会报时间超时,,而且上面正确的代码在visual studio上运行不了,但在网页上可以过