[ACdream]哗啦啦族的24点游戏[dfs][暴力][精度]

C - 哗啦啦族的24点游戏

Time Limit:  2000/1000MS (Java/Others)     Memory Limit:  128000/64000KB (Java/Others)
Submit  Status

Problem Description

哗啦啦族的小Q是一个狂热的24点爱好者,24点就是给你一串数字,问你是否通过加减乘除括号构成24点。
唐老师也觉得这个很好玩,就决定考考小q,给你4个数,你用加减乘除和括号,是否能构成24点呢?

 

 

Input

第一行t,表示有多少组测试数据,1<=t<=50

接下来t行,每行4个数字,表示每个数都是多少,1<=a[i]<=13

Output

对于每一次询问,如果能够凑成24点,输出yes,否则输出no

Sample Input

2
3 3 8 8
1 1 1 1

Sample Output

yes
no

Hint

3 3 8 8

就可以构造出 8 ÷ (3 – 8 ÷ 3)=24


题意分析:给出n个测试点,每个测试点有四个数字,问:通过加、减、乘、除四种运算,能不能算出24点,如果能,输出"yes",否则"no"。

解题思路:四个数字,四种运算,感觉暴力枚举下去还是可行的,就开干吧!(要注意除法会残留小数,这个精度处理是个问题!我的做法是把它转换为字符串比较(目前直接使用eps处理精度了))

个人感受:在WA了一发之后,发现自己的程序还有两个问题没解决:1.精度问题。2.没有考虑除法,减法可以两个数互换。交第二发的时候没想过A的,结果就喜出望外了XD(OJ更改了数据,之前的代码也被叉掉了XD,重新更新了AC代码ORZ 2015.6.10)

具体代码如下:

#include<cmath>
#include<iostream>
using namespace std;
const double eps = 1e-10;
const int MAXN = 4;
int number[MAXN];

bool search(int n)
{
    if (n==1)
    {
        if (fabs(number[0] - 24.0) < eps)
            return true;
        else
            return false;
    }
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            if (i != j)
            {
                double a = number[i], b = number[j];   //取出两个数
                number[j] = number[n - 1];    //将最后一个数提到前面(因为后期只遍历n - 1个数
            
                number[i] = a + b;
                if (search(n - 1)) return true;
            
                number[i] = a - b;
                if (search(n - 1)) return true;
                
                number[i] = a * b;
                if (search(n - 1)) return true;
            
                number[i] = a / b;
                if (search(n - 1)) return true;
            
                number[i] = a;   //恢复
                number[j] = b;
            }
        }
    }
    return false;
} 
int main()
{
    int t;
    cin >> t;
    while (t --)
    {
        for (int i = 0; i < 4; i++)
            cin >> number[i];
        if (search(4))
            cout << "yes\n";
        else
            cout << "no\n";
    }
    return 0;
}

你可能感兴趣的:(search,DFS,ACdream)