dfs——洛谷1149

P1149 [NOIP2008 提高组] 火柴棒等式 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

 

思路:用dfs搜索每种情况,符合要求的就计数

1.这道题刚开始没注意到数字可以组合起来变成多位数,因此需要提前处理每个多位数需要的火柴数。

2.在dfs搜索的时候,for循环一定要用if判断条件,这样会节省很多时间,纯裸代码会tle。

3.在dfs搜索的时候,结束条件一定要分步写。如果直接写a并且b,则会让u一直累加,dfs到了规定的规格就应该停下来,return回去。

4.多位数最大的值如何求出来是1111:因为n小于等于24,而且最大的数应该是全部由1构成,所以最多能1111,如果是1112,则超过了24。

 

 

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 int a[1200]={6, 2, 5, 5, 4, 5, 6, 3, 7, 6};
 5 int ans,b[5];
 6 int n;
 7 
 8 void dfs(int u,int sum)
 9 {
10     if(u>3)        //不要直接写&&sum+4==n&&b[1]+b[2]==b[3],会使得u继续累加下去 
11     {
12         if(sum+4==n&&b[1]+b[2]==b[3]) ans++;
13         return ;
14     }
15     
16     for(int i=0;i<=1111;i++)        //所有多位数 
17     {
18         if(sum+4+a[i]<=n)        //如果火柴总数没超过题中要求的,再继续累加。 
19         {                        //超过了就continue,节省时间 
20             b[u]=i;
21             dfs(u+1,sum+a[i]);
22             b[u]=0;
23         }
24     
25     }
26 }
27 
28 int main()
29 {
30     
31     scanf("%d",&n);
32     for(int i=10;i<=1111;i++)        //预处理所有多位数需要的火柴数 
33     {
34         a[i]=a[i/10]+a[i%10];
35     }
36     dfs(1,0);
37     
38     printf("%d\n",ans);
39     
40     
41     return 0;
42 }

 

posted @ 2022-02-08 14:33  wellerency  阅读(50)  评论(0编辑  收藏  举报