The partial sum problem(dfs)

来源:互联网 发布:知乎离职员工 编辑:程序博客网 时间:2024/06/05 14:41

The partial sum problem

时间限制:1000 ms  |  内存限制:65535 KB
难度:2
描述
One day,Tom’s girlfriend give him an array A which contains N integers and asked him:Can you choose some integers from the N integers and the sum of them is equal to K. 
输入
There are multiple test cases.
Each test case contains three lines.The first line is an integer N(1≤N≤20),represents the array contains N integers. The second line contains N integers,the ith integer represents A[i](-10^8≤A[i]≤10^8).The third line contains an integer K(-10^8≤K≤10^8).
输出
If Tom can choose some integers from the array and their them is K,printf ”Of course,I can!”; other printf ”Sorry,I can’t!”.
样例输入
41 2 4 71341 2 4 715
样例输出
Of course,I can!Sorry,I can't!
 /*分类:来源:思路:We are giants.create by Lee_SD on 2017/4/*/#include<queue>#include<iostream>#include<algorithm>#include<cmath>#include<stack>#include<string.h>#include<stdio.h>using namespace std;int n,a[22],sum;int vis[22];int flag;void dfs(int num,int cnt){if(num>n||cnt>sum||flag)return;if(cnt==sum){flag=1;return;}dfs(num+1,cnt);dfs(num+1,cnt+a[num]);}int main(){while(scanf("%d",&n)!=EOF){for(int i=0;i<n;i++)scanf("%d",&a[i]);scanf("%d",&sum);flag=0;dfs(0,0);if(flag)printf("Of course,I can!\n");elseprintf("Sorry,I can't!\n");}}        

0 0