北京大学 程序设计与算法(二) 递归 算24

算24

给出4个小于10个正整数,你可以使用加减乘除4种运算以及括号把这4个数连接起来得到一个表达式。现在的问题是,是否存在一种方式使得得到得表达式得结果等于24。

这里加减乘除以及括号的运算结果和运算的优先级跟我们平常的定义一致。

输入

输入数据包括多行,每行给出一组测试数据,包括4个小于10个正整数。最后一组测试数据种包括4个0,表示输入的结束,这组数据不用处理。

输出

对于每一组测试数据,输出一行,如果可以得到24,输出“YES”;否则,输出”no”.

思路:
n个数算24,必有两个数先算。这两个数算的结果,和剩余n-2个数,就构成了n-1个数求24的问题。

枚举先算的两个数,以及这两个数的运算方式。

边界条件:一个数算24直接报出yes或no

注意:浮点数比较是否相等,不能用==

程序

#include<iostream>

#include<cmath>

using namespace std;

double a[5];

#define EPS 1e-6

bool isZero(double x){

       return fabs(x)<=EPS;

}

bool count24(double a[],int n)

{//用数组 a里的n个数

       if(n==1){

              cout<<a[0]<<endl;

              if(isZero(a[0]-24))

              return true;

              else

              return false;

       }

       double b[5];

       for(int i=0;i<n-1;++i)

       for(int j=i+1;j<n;++j){//枚举两个数的组合

       int m=0;//还剩下两个数,m=n-2

              for(int k=0;k<n;++k)

                     if(k!=i&&k!=j)b[m++]=a[k];//把其余数放入b

             

                     b[m]=a[i]+a[j];

                     if(count24(b,m+1))return true;

                     b[m]=a[i]-a[j];

                     if(count24(b,m+1))return true;

                     b[m]=a[j]-a[i];

                     if(count24(b,m+1))return true; 

                     b[m]=a[j]*a[i];

                     if(count24(b,m+1))return true; 

                     if(!isZero(a[j])){

                            b[m]=a[i]/a[j];

                            if(count24(b,m+1))

                            return true;

                     }

                     if(!isZero(a[i])){

                            b[m]=a[j]/a[i];

                            if(count24(b,m+1))

                            return true;

                     }

              }

      

       return false;

       }

int main(){

       for(int i=0;i<4;i++){cin>>a[i];

       }

       if(count24(a,4))cout<<"Yes"<<endl;

       else cout<<"no"<<endl;

}

猜你喜欢

转载自www.cnblogs.com/Invictus-Gaming/p/12398281.html
今日推荐