zoukankan      html  css  js  c++  java
  • 递归-24点

    ....又是以前虐过我的期末习题..哪里摔倒就哪里爬起来吧

     1 #include<iostream>
     2 #include<math.h>
     3 #define  N 1e-3
     4 using namespace std;
     5 
     6 bool IsZero(double a){
     7     return abs(a) < N;
     8 }
     9 bool count24(double a[],int n)//递归传数得知道传入几个以及剩下的数的数组
    10 {
    11   if(IsZero(a[0]-24)) {
    12 
    13      return true;
    14   }
    15 if(n==1)
    16     return false;
    17 
    18     double x,y;
    19     double b[10];
    20     int m=0;
    21     for (int i = 0; i < n-1; ++i) {
    22         for (int j = i+1; j < n; ++j) {
    23             for (int k = 0; k < n; ++k) {
    24                 if(k!=i&&k!=j)
    25                 b[m++]=a[k];//顺便b有多少也得出来了
    26 
    27             }
    28             //cout<<m;
    29             b[m]=a[i]+a[j];
    30             if(count24(b,m+1))
    31                 return true;
    32             b[m]=a[i]-a[j];
    33             if(count24(b,m+1))
    34                 return true;
    35             b[m]=a[j]-a[i];
    36             if(count24(b,m+1))
    37                 return true;
    38             b[m]=a[i]*a[j];
    39             if(count24(b,m+1))
    40                 return true;
    41             //cout<<m;
    42             if(!IsZero(a[i])){
    43                 //cout<<"in";
    44                 b[m]=a[j]/a[i];
    45                 if(count24(b,m+1))
    46 
    47                     return true;
    48             }
    49             if(!IsZero(a[j])){
    50                 //cout<<"s";
    51                 b[m]=a[i]/a[j];
    52                 if(count24(b,m+1))
    53                     return true;
    54             }
    55 
    56 
    57             
    58         }
    59         
    60     }
    61     return false;//所有的循环都不行,才可以return false
    62 }
    63 int main(){
    64     double a[10];
    65     for (int i = 0; i < 4; ++i) {
    66         cin>>a[i];
    67         
    68     }
    69     if(count24(a,4))
    70         cout<<"yes";
    71     else
    72         cout<<"no";
    73 
    74 
    75 
    76 }

    又是感觉自己傻乎乎的一天.

    把b[m]=a[i]?a[j]写成m++

    还觉得没啥毛病,,,

    关键是,他每次都加加,就不知能把m加到多少了呜呜呜

    好多细节得注意呀呜呜呜

  • 相关阅读:
    JAVA应用apache httpclient探测http服务
    C#中字符串与byte[]相互转换
    C#中位、字节等知识
    #JAVA操作LDAP
    C#正则表达式判断字符串是否是金钱
    【IDEA】使用Maven骨架创建JavaWeb项目
    【IDEA】回退操作记录
    【SpringMVC】IDEA 不识别webapp的解决办法
    【Layui】16 表单元素 Form
    【Layui】15 日期时间选择器 Laydate
  • 原文地址:https://www.cnblogs.com/zhmlzhml/p/13256215.html
Copyright © 2011-2022 走看看