Counting DP-integer division

Original title portal

Analysis 1

According to the meaning of the question, this question is seeking a combination, regardless of order

This problem can be transformed into a complete backpack problem. The backpack capacity is n and there are n kinds of items. The weight of these items is 1 to n, and each item can be taken unlimited times. Isn't this the complete knapsack problem that I did before!

Backpack problem blog link

In the complete knapsack problem, the count is the maximum value of the total value. This problem is counting. We only need to change the maximum value operation in the original state equation to an accumulation operation to find all the number of solutions.

This question can also be optimized in a way similar to a complete knapsack. The detailed process is already in the knapsack problem blog (I wrote it lazily). We can use a similar way to optimize the two-dimensional into one-dimensional

Code 1

#include <bits/stdc++.h>
using namespace std;
const int N=1010,MOD=1e9+7;
int n;
int f[N];
int main()
{
    
    
    cin>>n;
    f[0]=1;
    for(int i=1;i<=n;i++)
        for(int j=i;j<=n;j++) 
            f[j]=(f[j]+f[j-i])%MOD;
    cout<<f[n]<<endl;
    return 0;
}

Analysis 2

f[i][j] represents the number of schemes
whose sum is i and exactly represented as the sum of j numbers. For the state calculation of f[i][j], the state can be divided into two categories.
1. The minimum value of the scheme is 1. f[i-1][j-1] means the sum is subtracted by 1, and the required number is also reduced by one
. The minimum value in the scheme is greater than 1, and f[ij][j] means that all numbers are subtracted by 1, so The number of required numbers remains the same

Code 2

#include <bits/stdc++.h>
using namespace std;
const int N=1010,MOD=1e9+7;
int n;
int f[N][N];
int main()
{
    
    
    cin>>n;
    f[0][0]=1;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=i;j++)
            f[i][j]=(f[i-1][j-1]+f[i-j][j])%MOD;
    int res=0;
    for(int i=1;i<=n;i++) res=(res+f[n][i])%MOD;
    cout<<res<<endl;
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_46126537/article/details/112993243