Parts and problems (Nanyang oj1058) (DFS)

Source: Internet
Author: User
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
 
   
Simple Deep Search
#include<stdio.h>int n,k,a[30],visit[30],ans,ok;int dfs(int pos){if(ans>=k){if(ans==k){if(!ok){    ok=1;printf("YES\n");}for(int i=0;i<n;i++)    if(visit[i]) printf("%d ",a[i]);printf("\n");}return ok;}for(int i=pos;i<n;i++) {   ans+=a[i];   visit[i]=1;   dfs(i+1);   ans-=a[i];   visit[i]=0;}}int main(){while(scanf("%d %d",&n,&k)==2){for(int i=0;i<n;i++){scanf("%d",&a[i]);visit[i]=0;}ok=ans=0;dfs(0);if(!ok)printf("NO\n");}return 0;}

Parts and problems (Nanyang oj1058) (DFS)

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.