CSU - 1600 Twenty-four point

Given four numbers, can you get twenty-four through the addition, subtraction, multiplication, and division? Each number can be used only once.

Input

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).

Output

For each case, print the “Yes” or “No”. If twenty-four point can be get, print “Yes”, otherwise, print “No”.

Sample Input
2 2 3 9
1 1 1 1 
5 5 5 1
Sample Output
Yes
No
Yes
Hint

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");
    }
}


發佈了79 篇原創文章 · 獲贊 1 · 訪問量 8918
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章