输入包括多行,包括4个小于10个正整数,最后一组测试数据中包括4个0表示输入结束。
输出如果可以得到24,输出YES,否则NO
样例
5 5 5 1
1 1 4 2
0 0 0 0
输出
YES
NO
题意就是给出4个数能否通过±*/四种运算得到24点。
思路就是先想出第一步要做什么,先找出2个数进行4种运算,这样就剩下3个数了(一个数是两个数运算后的,还有两个原来的数),再挑出两个。。。剩下一个的时候看看是不是24就可以了(注意有除法,浮点数不能用==,要用那个数-24再fabs看看是否小于一个误差1e-6)
代码
#include<iostream>
#include<cmath>
using namespace std;
#define EPS 1e-6
bool iszero(double n)
{
if(fabs(n)<EPS)
return true;
else return false;
}
bool count(double a[],int n)
{
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;//还剩下m个数,m=n-2
//把剩余的数放入b
for(int k=0;k<n;k++)
if(k!=j&&k!=i) b[m++]=a[k];
//加法
b[m]=a[i]+a[j];
if(count(b,m+1))
return true;
//减法
b[m]=a[i]-a[j];
if(count(b,m+1))
return true;
b[m]=a[j]-a[i];
if(count(b,m+1))
return true;
//乘法
b[m]=a[i]*a[j];
if(count(b,m+1))
return true;
//除法 ,注意余数不为0
if(!iszero(a[i]))
{
b[m]=a[j]/a[i];
if(count(b,m+1))
return true;
}
if(!iszero(a[j]))
{
b[m]=a[i]/a[j];
if(count(b,m+1))
return true;
}
}
}
return false;
}
int main()
{
double a[5];
while(true)
{
for(int i=0;i<4;i++)
cin>>a[i];
if(a[0]==0&&a[1]==0&&a[2]==0&&a[3]==0) break;
bool yes=count(a,4);
if(yes) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
return 0;
}