(2.18) The number of multiple set combinations

Title (DP)

Insert picture description here
Insert picture description here

Code

In order not to count repeatedly, it is best to handle the same kind of items at once.
dp[i+1][j] := The total number of combinations of taking out j items from the first i kinds of items O(nm 2 )
Taking out j items from the previous i kinds of items, you can first take out jk items from the first i-1 kinds of items, and then Take out k items from the i-th species and add them in
Insert picture description here

O(nm)
Insert picture description here
Insert picture description here

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;

const int MAX_N = 1000; 
const int MAX_M = 1000;
int dp[MAX_M+1][MAX_N+1]; // DP数组 

//输入 
int n = 3;   
int m = 3;
int a[3] = {
    
    1, 2, 3};
int M = 10000;

void solve(){
    
    
	// 一个都不取的方法总是只有一种
	for(int i = 0 ; i <= n ; i ++)
		dp[i][0] = 1;
	for(int i = 0 ; i < n ; i ++)
		for(int j = 1 ; j <= m ; j ++){
    
    
			if(j-1-a[i] >= 0) // 在有取余的情况下,避免减法运算的结果出现负数 
				dp[i+1][j] = (dp[i+1][j-1] + dp[i][j] - dp[i][j-1-a[i]] + M) % M;
			else
				dp[i+1][j] = (dp[i+1][j-1] + dp[i][j]) % M;
		}
	printf("%d\n", dp[n][m]);					 
} 	


int main(){
    
    	
	solve(); 
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_36321330/article/details/106925166