李白打酒

来源:互联网 发布:淘宝价格法2017 编辑:程序博客网 时间:2024/06/02 19:42
    话说大诗人李白,一生好饮。幸好他从不开车。一天,他提着酒壶,从家里出来,酒壶中有酒2斗。他边走边唱:
        无事街上走,提壶去打酒。
        逢店加一倍,遇花喝一斗。
    这一路上,他一共遇到店5次,遇到花10次,已知最后一次遇到的是花,他正好把酒喝光了。
    请你计算李白遇到店和花的次序,可以把遇店记为a,遇花记为b。则:babaabbabbabbbb 就是合理的次序。像这样的答案一共有多少呢?请你计算出所有可能方案的个数(包含题目给出的)。

1、回溯法

#include<stdio.h>int count=0;int wine, int shop, int flower;void backtrack(int t){if(t==15){if(shop==5 && flower==9 && wine==1)count++;return;}else{shop++; wine=wine*2; backtrack(t+1);shop--; wine=wine/2; flower++; wine=wine-1; backtrack(t+1);flower--; wine=wine+1; }}int main(){wine=2;shop=0; flower=0;backtrack(1);printf("the number is %d.\n",count);return 0;}

2、暴力搜索
#include <stdio.h>  #include <math.h>    int main()  {int wine;int flower,shop;int num;int count=0;int i,j;for(num=0;num<pow(2,14);num++){//二进制分解flower=0; shop=0; wine=2;j=num;for(i=0;i<14;i++){if(j%2==0){flower++;wine=wine-1;}else{shop++;wine=wine*2;}j=j/2;}if(shop==5 && flower==9 && wine==1)count++;}printf("the number is %d.\n",count);          return 0;  }  




3、最笨的办法

#include <stdio.h>  #include <math.h>    int main()  {int wine, flower,shop;int count=0;int a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14;for(a1=0;a1<2;a1++){for(a2=0;a2<2;a2++){for(a3=0;a3<2;a3++){for(a4=0;a4<2;a4++){for(a5=0;a5<2;a5++){for(a6=0;a6<2;a6++){for(a7=0;a7<2;a7++){for(a8=0;a8<2;a8++){for(a9=0;a9<2;a9++){for(a10=0;a10<2;a10++){for(a11=0;a11<2;a11++){for(a12=0;a12<2;a12++){for(a13=0;a13<2;a13++){for(a14=0;a14<2;a14++){flower=0; shop=0; wine=2;if(a1==0){ flower++; wine=wine-1;}else{shop++; wine=wine*2;}if(a2==0){ flower++; wine=wine-1;}else{shop++; wine=wine*2;}if(a3==0){ flower++; wine=wine-1;}else{shop++; wine=wine*2;}if(a4==0){ flower++; wine=wine-1;}else{shop++; wine=wine*2;}if(a5==0){ flower++; wine=wine-1;}else{shop++; wine=wine*2;}if(a6==0){ flower++; wine=wine-1;}else{shop++; wine=wine*2;}if(a7==0){ flower++; wine=wine-1;}else{shop++; wine=wine*2;}if(a8==0){ flower++; wine=wine-1;}else{shop++; wine=wine*2;}if(a9==0){ flower++; wine=wine-1;}else{shop++; wine=wine*2;}if(a10==0){ flower++; wine=wine-1;}else{shop++; wine=wine*2;}if(a11==0){ flower++; wine=wine-1;}else{shop++; wine=wine*2;}if(a12==0){ flower++; wine=wine-1;}else{shop++; wine=wine*2;}if(a13==0){ flower++; wine=wine-1;}else{shop++; wine=wine*2;}if(a14==0){ flower++; wine=wine-1;}else{shop++; wine=wine*2;}if(shop==5 && flower==9 && wine==1)count++;}}}}}}}}}}}}}}printf("the number is %d.\n",count);          return 0;  }  







0 0
原创粉丝点击