给出4个小于10的正整数,你可以用加减乘除4种运算以及括号把这四个数连接起来得到一个表达式。现在的问题是,是否存在一种方式使得得到的表达式的结果等于24.
这里加减乘除以及括号的运算结果和运算的优先级跟我们平常的定义一致(这里的除法定义是实数除法)。
如,对于5,5,5,1,我们知道5*(5-1/5) = 24,因此可以得到24.又比如,对于1,1,4,2,我们怎么都不能得到24.
样例输入:
5 5 5 1
1 1 4 2
0 0 0 0
样例输出:
YES
NO
NO
解析:
这里我们所采用的思路就是递归。每次从数组中取出两个数进行四则运算,得到一个数,于是数组中便减少了一个数,再把运算得到的数放到数组当中,再次进行函数的调用,最后就会只剩下一个数。这个数如果是24,那么就能够成功,否则就失败了。依据这种放法就能遍历所有的情况
#include <iostream>
#include <cmath>
using namespace std;
#define EPS 1e-6
bool isZero(double x){
return fabs(x) <= EPS;
}
bool count24(double a[],int n){
if(n == 1) {
if(isZero(a[0]-24))
return true;
else
return false;
}
double b[4];
for(int i = 0;i < n-1; ++i)
for(int j = i+1;j < n; ++j){
int m = 0;
for(int k = 0;k < n; ++k){
if(k != i && k != j)
b[m++] = a[k];
}
b[m] = a[i] + a[j];
if(count24(b,n-1)) return true;
b[m] = a[i] * a[j];
if(count24(b,n-1)) return true;
b[m] = a[i] - a[j];
if(count24(b,n-1)) return true;
b[m] = a[j] - a[i];
if(count24(b,n-1)) return true;
if(!isZero(a[j])){
b[m] = a[i]/a[j];
if(count24(b,n-1)) return true;
}
if(!isZero(a[i])){
b[m] = a[j]/a[i];
if(count24(b,n-1)) return true;
}
}
return false;
}
int main(){
double a[4];
while(true){
for(int i =0 ;i < 4; ++i){
cin >> a[i];
}
if(count24(a,4))
cout << "YES" <<endl;
else
cout << "NO" <<endl;
}
return 0;
}