Given four numbers, can you get twenty-four through the addition, subtraction, multiplication, and division? Each number can be used only once.
The 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.
解题思路:也是参考了大神的代码,因为数据较小,其实可以直接去dfs得出答案
代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
double EPS = 1e-10;
double num[4];
bool flag;
bool equel(double a, double b)
{
if(fabs(a - b) <= EPS)
return true;
return false;
}
void DFS(int n)
{
if(flag || (n == 1 && equel(num[0], 24)))
{
flag = true;
return;
}
for(int i = 0; i < n; i++)
{
for(int j = i + 1; j < n; j++)
{
double c1 = num[i], c2 = num[j];
num[j] = num[n - 1];
num[i] = c1 + c2;
DFS(n - 1);
num[i] = c1 - c2;
DFS(n - 1);
num[i] = c2 - c1;
DFS(n - 1);
num[i] = c1 * c2;
DFS(n - 1);
if(!equel(c2, 0))
{
num[i] = c1 / c2;
DFS(n - 1);
}
if(!equel(c1, 0))
{
num[i] = c2 / c1;
DFS(n - 1);
}
num[i] = c1;
num[j] = c2;
}
}
}
int main()
{
while(scanf("%lf %lf %lf %lf", &num[0], &num[1], &num[2], &num[3]) != EOF)
{
flag = false;
DFS(4);
printf("%s\n", flag ? "Yes" : "No");
}
}