Nyist oj Part 1 and question (DFS search), ojdfs

Source: Internet
Author: User

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 ;}





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.