CSU - 1600:Twenty-four point(DFS)

Twenty-four point

Time limit:1000 ms Memory limit:262144 kB OS:Linux


Problem Description

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


题意:

四个数字,任意次序,通过括号和四则运算是否能得到24。

解题思路:

爆搜。在前n个数里面任选两个求出结果,把结果放到前面一个数的位置,把a[n]放到后面那个数的位置,然后搜前n-1个数,最后的结果就存在a[0].


Code:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;

const double EPS=1e-8;
double a[5];
bool flag=false;
void dfs(int n)
{
    if(n<=0&&fabs(a[0]-24)<EPS)
    {
        flag=true;
        return;
    }
    if(flag||n<=0)
        return;
    for(int i=0;i<=n;i++)
    {
        for(int j=i+1;j<=n;j++)
        {
            double x=a[i],y=a[j];
            a[j]=a[n];

            a[i]=x*y;
            dfs(n-1);

            a[i]=x+y;
            dfs(n-1);

            a[i]=x-y;
            dfs(n-1);

            a[i]=y-x;
            dfs(n-1);

            if(fabs(x)>EPS)
            {
                a[i]=y/x;
                dfs(n-1);
            }
            if(fabs(y)>EPS)
            {
                a[i]=x/y;
                dfs(n-1);
            }

            a[i]=x,a[j]=y;
        }
    }
}

int main()
{

    while(scanf("%lf%lf%lf%lf",a,a+1,a+2,a+3)!=EOF)
    {
        flag=false;
        dfs(3);
        if(flag)
            printf("Yes\n");
        else
            printf("No\n");
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值