Programming Algorithm-code for combining multiple sets (C)

Source: Internet
Author: User

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


 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.