Programming Algorithm-multi-part and problem code (C)

Source: Internet
Author: User

Programming Algorithm-multi-part and problem code (C)
Multi-part and problem code (C)


Address: http://blog.csdn.net/caroline_wendy


Question: There are n numbers of different sizes a, each of which is m. Determine whether a number of numbers can be selected from these numbers to make their sum exactly K.


UseDynamic Planning (DP),

Method 1: Dp [I + 1] [j] = whether the first n digits can be used for adding and forming j,Time complexity O (nKm), Not optimal.


Method 2: Dp [I + 1] [j] = the maximum number of I-th instances that can be left when j is obtained by adding the first I-th number.Time complexity O (nK).

For example, n = 3, a = {3, 5, 8}, m = {3, 2}, K = 17.

I \ j 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Start 0 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
0 (3, 3) 3 -1 -1 2 -1 -1 1 -1 -1 0 -1 -1 -1 -1 -1 -1 -1 -1
1 (5, 2) 2 -1 -1 2 -1 1 2 -1 1 2 0 -1 -1 0 1 -1 -1 -1
2 (8, 2) 2 -1 -1 2 -1 2 2 -1 2 2 2 1 -1 1 1 -1 1 1

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 n = 3; int K = 17; int a [MAX_N] = {3, 5, 8 }; int m [MAX_N] = {3, 2}; bool dp [MAX_N + 1] [MAX_N + 1]; public: void solve () {dp [0] [0] = true; for (int I = 0; I
   
    
= 0) {dp [j] = m [I];} else if (j <a [I] | dp [j-a [I] <= 0) {dp [j] =-1 ;}else {dp [j] = dp [j-a [I]-1 ;}}} if (dp [K]> = 0) printf ("result = Yes \ n"); else printf ("result = No \ n ");}}; int main (void) {Program2 iP; iP. solve (); return 0 ;}
   
  
 

Output:

result = Yes










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.