Programming Algorithm-code for combining multiple sets (C)
Code for combining multiple sets (C)
Question: There are n types of items, and I type of items has a. Different types of items can be differentiated, but the same types cannot be differentiated.
How many methods can be used to retrieve m items from these items? Returns the remainder of a number M.
For example, there are n = 3 kinds of items, each a = {1, 2, 3}, 3 m = 3, result = 6 (0 + 0 + 3, 0 + 1 + 2, 0 + 2 + 1, 1 + 0 + 2, 1 + 1 + 1, 1 + 2 + 0 ).
UseDynamic Planning (DP).
Before I + 1 items out j = Before I + 1 items out J-1 + before I items out j-before I items out j-1-a.
Because take out the j-1-a, the last need to J-1, then a need to all take out, the first two are repeated, it must be all taken out.
Recursive Formula: dp [I + 1] [j] = dp [I + 1] [J-1] + dp [I] [j]-dp [I] [j-1-a]
Time complexity O (nm ).
Code:
/* * main.cpp * * Created on: 2014.7.20 * Author: spike *//*eclipse cdt, gcc 4.8.1*/#include
#include
class Program {static const int MAX_N = 100;int M=10000;int n=3, m=3;int a[MAX_N] = {1,2,3};int dp[MAX_N+1][MAX_N+1];public:void solve() {for (int i=0; i<=n; ++i) {dp[i][0] = 1;}for (int i=0; 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(result = %d, dp[n][m]);}};int main(void){Program iP;iP.solve();return 0;}
Output:
result = 6