生成函数表达式(求一个问题的方案数)

生成函数表达式: 求一个规定组合有多少个方案。通过模拟表达式运算来实现。


eg1:现有三种水果:苹果,梨子和西瓜。其中买苹果的数量必须为偶数个,梨子的数量必须为3的倍数,西瓜的数量不多于4个,问买n个水果,有多少种方案数?2018_Summer III K(比较像eg1)

苹果:

G1 = (x^0+x2+x4.....)

梨子:

G2 = (x^0+x^3+x^6+.....)

西瓜:

G3 = (x^0+x^1+x^2+x^3+x^4)

最后求G1*G2*G3的表达式中x^n前面的系数

eg2: 2018_Summer III U
输入一个整数,输出有多少种划分情况。
eg:  4有5种
 4 = 4; 
 4 = 3 + 1; 
 4 = 2 + 2; 
 4 = 2 + 1 + 1; 
 4 = 1 + 1 + 1 + 1; 
/*  我们来考虑整数1-n的贡献,即有多少个。
对于数字1:每次可以贡献1
G1(x) = x^0+x^1+x^2+...    (一共有多少个1)
对于数字2:每次可以贡献2
G2(x) = x^0+x^2+x^4+...    (一共有多少个2)
以此类推
........                 .............

Gn(x) = x^0+x^n                 (一共有多少个n)
然后将1-n所有数字的生成函数乘起来,求xn
的系数即可。*/

附上一题:

                                                                         Ignatius and the Princess III

"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

题解:输入一个整数n,输出有多少种划分情况。题解在上面的eg2。

import java.util.Arrays;
import java.util.Scanner;
public class Main {
	static Scanner scan = new Scanner(System.in);
	static int[] c1 = new int[300];
	static int[] c2 = new int[300];
 	public static void main(String[] args) {
		// TODO Auto-generated method stub
		while(scan.hasNext()){
			int n = scan.nextInt();
			Arrays.fill(c1, 0);
			Arrays.fill(c2, 0);
			for(int i=0;i<=n;i++){
				c1[i] = 1;
			}
			for(int i=2;i<=n;i++){
				for(int j=0;j<=n;j++)
					for(int k=0;j+k<=n;k+=i){     
						c2[j+k]+=c1[j];     //记录取j+k的系数
					}
				for(int j=0;j<=n;j++){
					c1[j] = c2[j];
					c2[j] = 0;
				}
			}
			System.out.println(c1[n]);
		}
 	}

}

 

你可能感兴趣的:(ACM)