首页 > 代码库 > Square Coins (HDU 1398) ———母函数模板详解

Square Coins (HDU 1398) ———母函数模板详解

                     Square Coins

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


Problem Description
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.

Input
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.

Output
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.

Sample Input
2 10 30 0

Sample Output
1 4 27
基本套模板,程序如下:
#include<stdio.h>
int main()
{
    int n,i,j,k;
    int c1[305],c2[305]; //c2为中间过渡量

    while(~scanf("%d",&n),n) //n表示要凑出的数
    {
        for(i=0; i<=n; i++)
            c1[i]=1,c2[i]=0; //将c1赋值为1表示变量系数初始为1
        for(i=2; i<=n; i++) //i指第i个表达式,即相乘的第i个括号
        {
            for(j=0; j<=n; j++) //j就是(前面i个表达式累乘的表达式)里第j个变量
                for(k=0; j+k<=n; k+=i*i)) //k表示第j个指数,即k其实是指基础指数(基本组成元素,比如本题的1,4,9...)
                    c2[j+k]+=c1[j]; //指数为k的变量的系数和,c2[j+k]其实就是指数为k的系数,c1[j]就是遍历前面括号的系数(一直在变化)
            for(j=0; j<=n; j++)
                c1[j]=c2[j],c2[j]=0; //把c2的值赋给c1,而把c2初始化为0,因为c2每次是从一个表达式中开始的
        }
        printf("%d\n",c1[n]); //输出指数为n变量的系数,即方法数
    }
    return 0;
}

这是我看了n遍百度,最后自己理解写的,如解释有误或不详请指正