Twenty-four point CSU - 1600

本文介绍了一种通过编程解决经典数学游戏“二十四点”的方法。使用递归算法结合加减乘除运算,对输入的四个数字尝试所有可能的组合方式以达到目标值24,并考虑了浮点数运算的精度问题。

摘要生成于 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

二十四点,题意和思路都很明确,考验代码能力……
每层搜索创建一个数组,从上一层的数组中挑两个数组合,将结果和剩下的数存入新数组,传递到下一层,注意浮点数精度

#include <iostream>
#include <stdio.h>
#include <math.h>
using namespace std;
double n[4];
bool dfs(double t[],int cot){
    double a;
    int i,j,k,l;
    double s[4];
    if(cot==1){
        if(fabs(t[0]-24.0)<1e-8){
            return true;
        }else{
            return false;
        }
    }
    for(i=0;i<cot;i++){
        for(j=0;j<cot;j++){
            if(i!=j){
                l=0;
                for(k=0;k<cot;k++){
                    if(k!=i&&k!=j){
                        s[l]=t[k];
                        l++;
                    }
                }
                s[l]=t[i]+t[j];
                if (dfs(s,cot-1)) return true;
                s[l]=t[i]-t[j];
                if (dfs(s,cot-1)) return true;
                s[l]=t[j]-t[i];
                if (dfs(s,cot-1)) return true;
                s[l]=t[i]*t[j];
                if (dfs(s,cot-1)) return true;
                if(t[i]!=0){
                    s[l]=t[j]/t[i];
                    if (dfs(s,cot-1)) return true;
                }
                if(t[j]!=0){
                    s[l]=t[i]/t[j];
                    if (dfs(s,cot-1)) return true;
                }
            }
        }
    }
    return false;
}
int main()
{
    while((scanf("%lf %lf %lf %lf",&n[0],&n[1],&n[2],&n[3]))!=EOF){

        if(dfs(n,4)){
            printf("Yes\n");
        }else{
            printf("No\n");
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值