和 (DFS)
和
Time Limit: | 1000MS | Memory Limit: | 65536KB |
Total Submissions: | 177 | Accepted: | 93 |
Description:
现给定一个含有n个元素的数组A,要求:从这n个数中选择一些数,这些数的和恰好为k
Input:
多组测试数据。第一行为n(1<=n<=20) 第二行为n个整数,每个数的范围为(-10^8≤A[i]≤10^8) 第三行为整数k(-10^8≤k≤10^8).
Output:
如果能够达到目的,输出”Of course,I can!”; 否则输出”Sorry,I can’t!”.
Sample Input:
4 1 2 4 7 13 4 1 2 4 7 15
Sample Output:
Of course,I can! Sorry,I can't!
1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 using namespace std; 5 int a[25]; 6 int vis[250]; 7 int n,m,flag; 8 void dfs(int i,int sum) 9 { 10 if(i<n&&!vis[i]){ 11 vis[i]=1; 12 if(sum+a[i]==m){ 13 flag=1; 14 }else if(sum+a[i]<m){ 15 dfs(i+1,sum+a[i]); 16 dfs(i+1,sum); 17 }else{ 18 dfs(i+1,sum); 19 } 20 vis[i]=0; 21 } 22 } 23 int main() { 24 while(cin>>n){ 25 for(int i=0;i<n;i++) cin>>a[i]; 26 cin>>m; 27 flag=0; 28 dfs(0,0); 29 if(flag) cout<<"Of course,I can!"<<endl; 30 else cout<<"Sorry,I can't!"<<endl; 31 } 32 return 0; 33 }