Ignatius and the Princess III(母函数/生成函数)

题面

"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!"

是个组合拆分问题,去查了一下,有个母函数/生成函数,将加变成了乘,即移到指数上,两项相乘,指数相加

Ignatius and the Princess III(母函数/生成函数)_第1张图片

 一定要落实到代码上,模拟乘法

#include 
using namespace std;
const int N = 1e5 + 10;
int a[N], b[N];//a存对应指数i下的系数, b用来过度当中间值
int n;
int main()
{
    while(~scanf("%d", &n))
    {
        for (int i = 0; i <= n; i ++ )//用第一个括号式初始一下每个项的值
        {
            a[i] = 1;
        }
        for (int i = 2; i <= n; i ++ )//枚举第几个括号式(2~n)
        {
            for (int j = 0; j <= n; j ++ )//j代表此时指数的从小到大的项
            {
                for (int k = 0; k + j <= n; k += i)//k代表指数(k每次+i是第i个括号的递增)
                {
                    b[k + j] += a[j];//对应乘起来变成指数k+j
                }
            }
            for (int j = 0; j <= n; j ++ )
            {
                a[j] = b[j];
                b[j] = 0;
            }
        }
        
        cout << a[n] << endl;
    }

    return 0;
}

 

你可能感兴趣的:(算法,c++,学习)