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 <stdio. h> # include <memory. h> 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 <n; ++ I) {for (Int J = 0; j <= K; ++ J) {for (int K = 0; k <= m [I] & K * A [I] <= J; ++ K) {DP [I + 1] [J] | = DP [I] [J-K * A [I]; // or operation }}if (DP [N] [k]) printf ("result = Yes \ n "); else printf ("result = NO \ n") ;}}; class program2 {static const int max_n = 100; static const int max_k = 20; int n = 3; int K = 17; int A [max_n] = {3, 5, 8}; int M [max_n] = {3, 2}; int DP [max_k + 1]; public: void solve () {memset (DP,-1, sizeof (DP); DP [0] = 0; For (INT I = 0; I <n; ++ I) {for (Int J = 0; j <= K; ++ J) {If (DP [J]> = 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
Programming Algorithm-multi-part and problem code (c)