(CSU - 1600)Twenty-four point

(CSU - 1600)Twenty-four point

Time Limit: 1 Sec Memory Limit: 128 Mb Submitted: 737 Solved: 147

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

Hint

For the first sample, (2/3+2)*9=24.

题目大意:给出四个数,通过加减乘除能否算出24点。

思路:数据这么小,直接爆搜(dfs)即可。

#include<cstdio>
#include<cstring>
using namespace std;

const double eps=1e-8;
double a[5];

bool sgn(double x)
{
    return (x>-eps&&x<eps);
}

bool dfs(double a[],int n)//数组中n个数是否可以算出24点 
{
    double b[5];
    if(n==1&&sgn(a[1]-24)) return true;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
            if(i!=j)
            {
                int p=1;
                memset(b,0,sizeof(b));
                for(int k=1;k<=n;k++) 
                    if(k!=i&&k!=j) b[p++]=a[k];
                for(int k=1;k<=4;k++)
                {
                    if(k==1) b[p++]=a[i]+a[j];
                    else if(k==2) b[p++]=a[i]-a[j];
                    else if(k==3) b[p++]=a[i]*a[j];
                    else
                    {
                        if(!sgn(a[j])) b[p++]=a[i]/a[j];
                    }
                    if(dfs(b,n-1)) return true;
                    b[--p]=0;
                }
            }
    return false;
}

int main()
{
    while(scanf("%lf%lf%lf%lf",&a[1],&a[2],&a[3],&a[4])!=EOF)
    {
        if(dfs(a,4)) 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、付费专栏及课程。

余额充值