HDU 1028 Ignatius and the Princess III(母函數)

原題

Ignatius and the Princess III

Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u

Description

"Well, it seems the first problem is too easy. I will let you know how foolish you are later." feng5166 says.

"The second problem is, given an positive integer N, we define an equation like this:
N=a[1]+a[2]+a[3]+...+a[m];
a[i]>0,1<=m<=N;
My question is how many different equations you can find for a given N.
For example, assume N is 4, we can find:
4 = 4;
4 = 3 + 1;
4 = 2 + 2;
4 = 2 + 1 + 1;
4 = 1 + 1 + 1 + 1;
so the result is 5 when N is 4. Note that "4 = 3 + 1" and "4 = 1 + 3" is the same in this problem. Now, you do it!"

Input

The input contains several test cases. Each test case contains a positive integer N(1<=N<=120) which is mentioned above. The input is terminated by the end of file.

Output

For each test case, you have to output a line contains an integer P which indicate the different equations you have found.

Sample Input

4
10
20

Sample Output

5
42
627

題意

給出一個數字,將它表示爲比它小的數字之和,數字可以重複,問有多少種表示方式。

涉及知識及算法

母函數

代碼

//母函數
//G(x) = (1 + x^1 + x^2..+x^n)(1 + x^2 + x^4 + x^6 + ...)(1 + x^3 + x^6 +..)(..)(1 + x^n)
//第一個表達式(1 + x^1 + x^2..+x^n)中 x的指數代表【解中'1'的出現次數】 比如x^2 = x^(1 * 2) 這是'1'出現了兩次 x^3 = x^(1 * 3) '1'出現3次
//相似的 第二個表達式(1 + x^2 + x^4 + x^6 + ...) x^4 = x^(2 * 2) '2'出現兩次 x^6 = x^(2 * 3) '1'出現3次
//...以此類推 【* 1(0次項) 是代表該數字出現次數爲0】
//乘法原理的應用:每一個表達式 表示的都是 某個變量的所有取值【比如第一個表達式 表示'1'可以取的值(即n拆分後'1'出現的次數)可以爲 {0,1,
//2...n}】
//每個變量的所有取值的乘積 就是問題的所有的解(在本問題中表現爲‘和’)
//例子:4 = 2 + 1 + 1就是  x^(1 * 2)【'1'出現2次】
//			* x^(2 * 1)【'2'出現1次】
//			* x^(3 * 0)【'3'出現0次】
//			* x^(4 * 0)【..】
//			的結果
//上述4個分式乘起來等於 1 * (x^4) 代表 4的一個拆分解
//所以 G(x)展開後 其中x^n的係數就是 n的拆分解個數
# include <stdio.h>

int main()
{
	int C1[123], C2[123], n;
	while(scanf("%d", &n) != EOF)
	{
	    //初始化 第一個表達式 目前所有指數項的係數都爲1
	    //C2爲輔助存儲
		for(int i = 0; i <= n; i++)
		{
			C1[i] = 1;
			C2[i] = 0;
		}
        //第2至第n個表達式
		for(int i = 2; i <= n; i++)
		{
            //C1爲前i-1個表達式累乘後各個指數項的係數
            //j標識的是這個計算之前的指數
			for(int j = 0; j <= n; j++)
			{
				for(int k = 0; j + k <= n; k += i)//k爲第i個表達式每個項的指數 第一項爲1【即x^(i * 0)】(指數k=0),
                                                                  // 第二項爲x^(i * 1)(指數爲k=i), 第三項爲x^(i * 2)... 所以k的步長爲i
				{
				    //(ax^j)*(x^k) = ax^(j+k) -> C2[j+k] += a  【第i個表達式每一項的係數都爲1; a爲C1[j]的值(x^j的系
                                    //  數);C2爲乘上第i個表達式後各指數項的係數】
					C2[j + k] += C1[j];
				}
			}
			for(int j = 0; j <= n; j++)//刷新當前累乘結果各指數項的係數
			{
				C1[j] = C2[j];
				C2[j] = 0;
			}
		}
		printf("%d\n",C1[n]);
	}
	return 0;
}

代碼轉自HDUOJ用戶zhbit_14_AAAAsuna ,附上鍊接http://acm.hdu.edu.cn/discuss/problem/post/reply.php?postid=21943&messageid=1&deep=0,向他表示感謝。
發佈了25 篇原創文章 · 獲贊 9 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章