Given four numbers, can you get twenty-four through the addition, subtraction, multiplication, and division? Each number can be used only once.
InputThe input consists of multiple test cases. Each test case contains 4 integers A, B, C, D in a single line (1 <= A, B, C, D <= 13).
For each case, print the “Yes” or “No”. If twenty-four point can be get, print “Yes”, otherwise, print “No”.
2 2 3 9 1 1 1 1 5 5 5 1
Yes No Yes
For the first sample, (2/3+2)*9=24.
给你四个数,每个数使用且仅能使用一次,问是否能得到24;
#include<stdio.h>
#include<cmath>
#include<string.h>
#include<iostream>
using namespace std;
double a[4];bool flag;
bool den(double a,double b)
{
if(fabs(a-b)<=1e-10)
return true;
return false;
}
void dfs(int t)
{
if(flag||(t==1&&den(a[0],24)))
{
flag=true;return;
}
for(int i=0;i<t;i++)
{
for(int j=i+1;j<t;j++)
{
double x1=a[i],x2=a[j];
a[j]=a[t-1];
a[i]=x1+x2;dfs(t-1);//直接在dfs中进行加减乘除运算,然后每dfs深入一次,相当在主治肝上分叉,这些分出来的枝条地位相同,这样不断
a[i]=x1-x2;dfs(t-1);//细分,就将所有的情况都考虑到了;就像二叉树一样,从根节点开始(递归开始时)不断向下分支;
a[i]=x2-x1;dfs(t-1);
a[i]=x1*x2;dfs(t-1);
if(!den(x1,0))
{
a[i]=x2/x1;dfs(t-1);
}
if(!den(x2,0))
{
a[i]=x1/x2;dfs(t-1);
}a[i]=x1;a[j]=x2;//将此层的数组复原,这样任意两个数进行运算都是在原来的数组上进行的,符合题意;
}
}
}
int main()
{
//freopen("1.txt","r",stdin);
while(cin>>a[0]>>a[1]>>a[2]>>a[3])
{
flag=false;
dfs(4);
printf("%s\n",flag?"Yes":"No");
}
return 0;
}