Contest2079 - 湖南多校对抗赛(2015.05.03) Problem A: Twenty-four point

Problem A: Twenty-four point

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 414  Solved: 62

[Submit][Status][Web Board]

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.

-----------------------------------

第一次去中南,今天之前还不会写搜索

思路:

初始时集合(元素可重复)中有4个数,取出两个进行四则运算,考虑顺序,减、除要算两次,即 a-b b-a a/b b/a ,加、乘 与顺序无关 , 这一步情况总数为 C(4,2) * 6 。

  

依此类推,进行第二步第三步,每一步结束后,集合中少一个数,直到集合中只剩一个数,判断这个数是否为 24

  

所有可能情况的总数为 C(4,2) * 6 * C(3,2) * 6 * 6

#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
const double eps=1e-6;  ///最大允许误差
double num[4];     ///double!!
bool dfs(int n){          ///n代表此时数组中还剩几个数
    if(n==1) {
        if(fabs(num[0]-24)<eps) return true;
        else return false;         ///n==1 return true/false
    }
    for(int i=0;i<n;i++)
     for(int j=i+1;j<n;j++){
        double a=num[i],b=num[j];
        num[j]=num[n-1];

        num[i]=a-b;  if(dfs(n-1)) return true;
        num[i]=a+b;  if(dfs(n-1)) return true;
        num[i]=a*b;  if(dfs(n-1)) return true;
        num[i]=b-a;  if(dfs(n-1)) return true;
        if(a) num[i]=b/a;  if(dfs(n-1)) return true;   ///分母
        if(b) num[i]=a/b;  if(dfs(n-1)) return true;

        num[i]=a,num[j]=b;   ///都不满足 恢复num[i],num[j] 继续搜索
       }
     return false;   ///不管怎么选都达不到24 此路不通
}

int main()
{
    while(~scanf("%lf",&num[0])){
        for(int i=1;i<4;i++)
            scanf("%lf",num+i);
        if(dfs(4)) printf("Yes\n");
        else printf("No\n");    /// YES NO 注意大小写...
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值