CSU-ACM2017暑期训练4-dfs F - Twenty-four point CSU - 1600

本文介绍了一种解决经典24点游戏问题的算法。通过递归深度优先搜索的方法,利用加减乘除运算组合,判断给定的四个数字是否能通过运算得到24。文章提供了详细的C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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.

              思路:用a[4】存数据,搜索时每两个两个进行计算,并且把结果放到下标小的里面,下标大的用他后面一个代替。

代码:


#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF = 1000000000;
const int maxn = 100;
int T,n,m;
int flag;
double a[4];


void dfs(int step)
{
    if(flag)
        return;
    if(step==3&&fabs(a[0]-24.0)<eps)
    {
        flag=1;
        return;
    }
    else
    {
        for(int i=0;i<=3-step;i++)
        {
            if(flag)
                return;
            for(int j=i+1;j<=3-step;j++)
            {
                double x,y;
                x=a[i];
                y=a[j];
                a[j]=a[3-step];
                a[i]=x+y;
                dfs(step+1);
                a[i]=x-y;
                dfs(step+1);
                a[i]=y-x;
                dfs(step+1);
                a[i]=x*y;
                dfs(step+1);
                if(fabs(x-0)>eps)
                {
                    a[i]=y/x;
                    dfs(step+1);
                }
                if(fabs(y-0)>eps)
                {
                    a[i]=x/y;
                    dfs(step+1);
                }
                a[i]=x;
                a[j]=y;
            }
        }
    }
}

int main()
{
	while(scanf("%lf%lf%lf%lf",&a[0],&a[1],&a[2],&a[3])!=EOF)
    {
        flag=0;
        dfs(0);
        if(!flag)
            printf("No\n");
        else
            printf("Yes\n");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值