HDOJ-1398 Square Coins(母函式)

weixin_34198583發表於2013-04-27

Square Coins

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


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
 

 

Source
 

 

Recommend
Ignatius.L
 
第一個用母函式寫的題,紀念下:
 1 /*
 2 構造母函式如下:
 3 G(x)=(1+x+x^2+x^3+...)*(1+x^4+x^8+x^12+...)*(1+x^9+x^18+...)...(1+x^17+x^34+...)
 4 */ 
 5 
 6 #include <cstdio>
 7 #include <iostream>
 8 
 9 using namespace std;
10 
11 int main()
12 {
13     int sum;
14     int c1[305], c2[305];
15     while(scanf("%d", &sum), sum)
16     {
17         for(int i = 0; i <= sum; ++i)
18         {
19             c1[i] = 1;//初始化為第一個括號各項的係數,之後再依次與後邊的合併更新 
20             c2[i] = 0;
21         }
22         
23 
24         for(int i = 2; i <= 17; ++i)// 共有17個大括號相乘 ,直接從第二個括號開始合併 
25         {
26             for(int j = 0; j <= sum; ++j)// 每次都合併到第一個括號中,這裡 j 代表第一個括號中的各項係數 
27             {
28                 for(int k = 0; k+j <= sum; k += i*i) //雖然括號之間是相乘關係,但是指數之間是相加關係 
29                 {
30                     c2[k+j] += c1[j]; // c2 陣列可以理解為每次存放的中間結果,因為每次都是後邊的括號與第一個括號可並,而後邊的括號係數都為一,所以只有第一個括號中的係數對合並後相應的係數有貢獻
31                 }
32             }
33             for(int j = 0; j <= sum; ++j)
34             {
35                 c1[j] = c2[j];
36                 c2[j] = 0;       // 記得每次合併一個括號後要把   c2 清零 
37             } 
38         }
39         printf("%d\n", c1[sum]);
40     }
41     return 0;
42 }

 

相關文章