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)