计蒜客 买书 dfs

题目:

https://www.jisuanke.com/course/2291/182236

思路:

递归解决,从第一本书开始,每本书都有两种选择:

//index是book里面每本书价格的下标,
//money是目前的费用,cnt是计数现在买了几本书

1.买
dfs(index+1,money+book[index],cnt+1);

2.不买

dfs(index+1,money,cnt);//不买index这本书,往下一本书走

不断的递归进行选择,直到得出结果。

 

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstdlib>
 4 #include<cstring>
 5 #include<queue>
 6 using namespace std;
 7 //计蒜客 买书
 8 int m,n,k;
 9 int book[33],vis[33];//book存价格
10 bool ok=false;//有没有解
11 //index是book里面每本书价格的下标,
12 //money是目前的费用,cnt是计数现在买了几本书
13 void dfs(int index,int money,int cnt)
14 {
15     if(index>n)
16     return;
17     if(money>m||cnt>k)//剪枝 
18     return;
19     
20     if(money==m&&k==cnt)//满足条件 
21     {
22         ok=true;
23         return;
24     }
25     
26     dfs(index+1,money,cnt);//不买index这本书,往下一本书走
27     dfs(index+1,money+book[index],cnt+1); 
28     
29 }
30 
31 int main() 
32 {
33     while(scanf("%d%d%d",&m,&n,&k)==3)
34     {
35         for(int i=0;i<n;i++)
36         {
37             scanf("%d",&book[i]);
38         }
39         memset(vis,0,sizeof(vis));
40         
41         ok=false;
42         dfs(0,0,0);
43         
44         if(ok)
45         printf("Yes\n");
46         else
47         printf("No\n");
48     }
49     return 0;
50 }

 

posted @ 2019-03-28 17:27  付玬熙  阅读(279)  评论(0编辑  收藏  举报