1. 程式人生 > >【完全揹包/母函式/遞推】HDU1028-Ignatius and the Princess III

【完全揹包/母函式/遞推】HDU1028-Ignatius and the Princess III

題目連結:http://acm.hdu.edu.cn/showproblem.php?pid=1028

Problem 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

完全揹包程式碼:

#include<iostream>
#include<cstring>
using namespace std;
const int maxn=120;
int dp[maxn];
//  完全揹包求方案數;
void CompletePack()
{
    memset(dp,0,sizeof(dp));
    dp[0]=1;        //  初始化
    for(int i=1;i<=maxn;i++){       //  填數字i;
        for(int j=i;j<=maxn;j++){   //  容量為j的方案數更新;
            dp[j]+=dp[j-i];
        }
    }
}
int main()
{
    int n;
    cin.sync_with_stdio(false);
    CompletePack();
    while(cin>>n){
        cout<<dp[n]<<endl;
    }
    return 0;
}

母函式程式碼:

#include<iostream>
using namespace std;
//  母函式
const int maxn=120;
int f[maxn]={0};        //  儲存對應指數的係數(方案數)
int tmp[maxn]={0};      //  臨時儲存分解一個因式的對應指數的係數
void faction(int N)
{
    for(int i=0;i<=N;i++)
        f[i]=1;     //  第一個數,所構成的方案數都是1;
    for(int i=2;i<=N;i++){      //  從第二個表示式開始
        //  因式逐個分解;
        for(int j=0;j<=N;j++)  //  表示式內從第一個開始(j表示的是指數);
            for(int k=0;k+j<=N;k+=i)   //  表示式指數增加值;
                tmp[j+k]+=f[j]; //  表示指數為j+k的係數;
        //  更新指數係數;
        for(int j=0;j<=N;j++){
            f[j]=tmp[j];
            tmp[j]=0;
        }
    }
}
int main()
{
    int n;
    cin.sync_with_stdio(false);
    faction(maxn);
    while(cin>>n){
        cout<<f[n]<<endl;
    }
    return 0;
}

遞推程式碼:

#include<iostream>
using namespace std;
const int maxn=121;
int f[maxn][maxn]={0};  //  f[i][j]表示組合成i值且組合數中最小數為j的方案數;
void faction(int N)
{
    for(int i=0;i<N;i++)
        f[0][i]=1;
    for(int i=1;i<N;i++){       //  所有可以組成的值;
        for(int j=1;j<=i;j++){  //  所組成的值的可能存在的數字;
            for(int k=j;k<=i;k++){  //  新增一個數字k,將更新方案數;
                f[i][j]+=f[i-k][k]; //  組合值為i-k,切最小數為k的方案數直接加上一個k就構成了新的組合值為i的方案;
            }
        }
    }
}
int main()
{
    faction(maxn);
    cin.sync_with_stdio(false);
    int n;
    while(cin>>n){
        cout<<f[n][1]<<endl;
    }
    return 0;
}