A38066. 算24给出 4 个小于10个正整数, 你可以使用加减乘除 4 种运算以及括号把这 4 个数连接起来得到一个表达式。 现在的问题是, 是否存在一种方式使得得到的表达式的结果等于24。 这里加减乘除以及括号的运算结果和运算的优先级跟我们平常的定义一致(这里的除法定义是实数除法) 。比如,对于 5,5, 5, 1 , 我们知道 5 * (5 – 1 / 5) =24, 因此可以得到 24。 又比如, …
填空题
困难
知识点
题目描述
算24
给出 4 个小于10个正整数, 你可以使用加减乘除 4 种运算以及括号把这 4 个数连接起来得到一个表达式。 现在的问题是, 是否存在一种方式使得得到的表达式的结果等于24。 这里加减乘除以及括号的运算结果和运算的优先级跟我们平常的定义一致(这里的除法定义是实数除法) 。比如,对于 5,5, 5, 1 , 我们知道 5 * (5 – 1 / 5) =24, 因此可以得到 24。 又比如, 对于 1 , 1 , 4, 2, 我们怎么都不能得到 24。
输入
输入数据包括多行, 每行给出一组测试数据, 包括 4 个小于 1 0 个正整数。 最后一组测试数据中包括 4个 0, 表示输入的结束, 这组数据不用处理。
输出
对于每一组测试数据, 输出一行, 如果可以得到 24, 输出“YES”; 否则, 输出“NO”。
样例输入
5 5 5 1
1 1 4 2
0 0 0 0
样例输出
YES
NO
参考答案
#include <iostream>
#include <cmath>
using namespace std;
double a[5];
#define EPS 1e-6
bool isZero(double x)//判断浮点数x是否为零
{
return fabs(x)<=EPS;
}
bool count24(double a[],int n)//算24
{//用数组里面的n个数算24
if(n==1)
{
//边界条件
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;
for(int k=0; k<n; k++) //将除选中的2个数(即i,j)以外的数存到数组b[]中
{
if(k!=i&&k!=j)
b[m++]=a[k];
}
//下面是取得两个数的四则运算情况,每种情况后面进行回调
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[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;
}
if(!isZero(a[j]))
{
b[m]=a[i]/a[j];
if(count24(b,m+1))
return true;
}
}
return false;
}
int main()
{
while(true)
{
for(int i=0; i<4; i++)
cin>>a[i];
if(isZero(a[0])&&isZero(a[1])&&isZero(a[2])&&isZero(a[3]))
break;
cout<<(count24(a,4) ? "YES":"NO")<<endl;
}
return 0;
}
上一题
下一题