Nyist oj Part 1 and question (DFS search), ojdfs
Partial and problem time limit: 1000 MS | memory limit: 65535 KB difficulty: 2
-
Description
-
Given integers a1, a2,... an, judge whether several numbers can be selected from them to make their sum exactly K.
-
Input
-
First, n and k, n represent the number of numbers, and k represent the sum of numbers.
Next, the number of n rows.
(1 <= n <= 20, which must not exceed the int range)
-
Output
-
If the sum can be k, "YES" is output, and the sum of which numbers is output in order of input. Otherwise, "NO" is output"
-
Sample Input
-
4 131 2 4 7
-
Sample output
-
YES2 4 7
-
Source
-
Typical questions
-
Uploaded
-
TC _ Yang zhuangliang
When searching simple questions, you must pay attention to the ending condition when recursion, that is, the critical condition to reduce the overhead of recursion;
The following code is used:
# Include <cstdio> # include <cstring> using namespace std; int a [30], n, k, sum; bool visit [30], flag; void dfs (int pos) {if (flag = true) return; if (sum> = k) {if (sum = k) {flag = true; printf ("YES \ n "); for (int I = 0; I <n; I ++) if (visit [I]) // mark printf ("% d", a [I]);} return; // here is the condition for Recursive termination. Adding an end condition here reduces the time consumption.} for (int I = pos; I <n; I ++) // The search process {sum + = a [I]; visit [I] = 1; dfs (I + 1); sum-= a [I]; visit [I] = 0 ;}} int main () {int I; while (scanf ("% d", & n, & k )! = EOF) {for (I = 0; I <n; I ++) scanf ("% d", & a [I]); memset (visit, 0, sizeof (visit); flag = false; dfs (0); if (! Flag) printf ("NO \ n");} return 0 ;}