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

给你四个数,每个数使用且仅能使用一次,问是否能得到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;
} 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值