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