蓝桥杯 历届试题 李白打酒



标题:李白打酒


    话说大诗人李白,一生好饮。幸好他从不开车。


    一天,他提着酒壶,从家里出来,酒壶中有酒2斗。他边走边唱:


    无事街上走,提壶去打酒。
    逢店加一倍,遇花喝一斗。


    这一路上,他一共遇到店5次,遇到花10次,已知最后一次遇到的是花,他正好把酒喝光了。 


    请你计算李白遇到店和花的次序,可以把遇店记为a,遇花记为b。则:babaabbabbabbbb 就是合理的次序。像这样的答案一共有多少呢?请你计算出所有可能方案的个数(包含题目给出的)。


    注意:通过浏览器提交答案。答案是个整数。不要书写任何多余的内容。



分析:

主要是运用递归搜索,找到所有的情况,遇店酒量加倍,遇花喝去一斗,两个递归对应两种情况,遍历得到所有的情况

c++代码:

01. #include<stdio.h>
02. #include<string>
03. #include<iostream>
04. using namespace std;
05. int t;
06. void digui(int j,int d,int h,string str)
07. {
08.  
09. if(d+h==15)
10. {
11. if(j==0)
12. {
13. int c=0;
14. for(int i=0; i<str.length(); i++)
15. if(str[i]=='b')
16. c++;
17. if(c==10&&str[14]=='b')
18. {
19. t++;
20. cout<<str<<endl;
21. }
22. }
23. return ;
24. }
25. digui(j*2,d+1,h,str+"a");
26. digui(j-1,d,h+1,str+"b");
27. }
28. int main()
29. {
30. digui(4,1,0,"a");
31. digui(1,0,1,"b");
32. printf("%d\n",t);
33. return 0;
34. }
Java代码:

  1. public class MrLBDaJiu {  
  2.   
  3.     public static void main(String[] args) {  
  4.   
  5.         digui(410"a");// 遇到店  
  6.         digui(101"b");// 遇到花  
  7.           
  8.         System.out.println(result);  
  9.   
  10.     }  
  11.   
  12.     static int result;  
  13.     private static void digui(int j, int d, int h, String str) {  
  14.   
  15.         if (d + h == 15) {  
  16.             if (j == 0) {  
  17.                 int count = 0;  
  18.                 for (int i = 0; i < str.length(); i++)  
  19.                     if (str.charAt(i) == 'b')  
  20.                         count++;  
  21.                 if (count == 10 && str.charAt(14) == 'b') {  
  22.                     result++;  
  23. //                  System.out.println(str);  
  24.                 }  
  25.             }  
  26.             return;  
  27.         }  
  28.   
  29.         digui(j * 2, d + 1, h, str + "a");  
  30.         digui(j - 1, d, h + 1, str + "b");  
  31.   
  32.     }  
  33. }









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值