【hihocoder 1304】搜索一·24点

【题目链接】:http://hihocoder.com/problemset/problem/1304

【题意】

【题解】

按照题目给的方法搜索就好;
那个方法很棒啊。
注意除0;
然后是浮点数的比较;
直接返回了一个Int型..爆炸了

    (((a$b)$c)$d)
    ((a$b)&(c$d))

    $操作对应
    1..6
    +,-,*,/,反-,反/


【Number Of WA

6

【完整代码】

#include <bits/stdc++.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define ms(x,y) memset(x,y,sizeof x)

typedef pair<int,int> pii;
typedef pair<LL,LL> pll;

const int dx[9] = {0,1,-1,0,0,-1,-1,1,1};
const int dy[9] = {0,0,0,-1,1,-1,1,-1,1};
const double pi = acos(-1.0);
const int N = 110;

int num[5],ope[4],a[5];
bool bo[5];

double cal(double a,int op,double b)
{
    if (op==1) return a + b;
    if (op==2) return a - b;
    if (op==3) return a * b;
    if (op==4)
    {
        if (fabs(b)<1e-6) return 2e8;
        return a/b;
    }
    if (op==5) return b-a;
    if (op==6)
    {
        if (fabs(a)<1e-6) return 2e8;
        return b/a;
    }
    return 233;
}

double js1()
{
    //(((a$b)$c)$d)
    double x,y,z;
    x = cal(num[1],ope[1],num[2]);
    if (x>1e8) return 233;
    y = cal(x,ope[2],num[3]);
    if (y>1e8) return 233;
    z = cal(y,ope[3],num[4]);
    if (z>1e8) return 233;
    return z;
}

double js2()
{
    double x,y,z;
    //((a$b)&(c$d))
    x = cal(num[1],ope[1],num[2]);
    if (x>1e8) return 233;
    y = cal(num[3],ope[3],num[4]);
    if (y>1e8) return 233;
    z = cal(x,ope[2],y);
    if (z>1e8) return 233;
    return z;
}

bool choose_ope(int dep)
{
    if (dep>3)
    {
        if (fabs(js1()-24)<1e-12) return true;
        if (fabs(js2()-24)<1e-12) return true;
        return false;
    }
    rep1(i,1,6)
    {
        ope[dep] = i;
        if (choose_ope(dep+1)) return true;
    }
    return false;
}

bool choose_num(int dep)
{
    if (dep>4)
    {
        if (choose_ope(1)) return true;
        return false;
    }
    rep1(i,1,4)
        if (!bo[i])
        {
            bo[i] = true;
            num[dep] = a[i];
            if (choose_num(dep+1)) return true;
            bo[i] = false;
        }
    return false;
}

int main()
{
    //freopen("F:\\rush.txt","r",stdin);
    ios::sync_with_stdio(false),cin.tie(0);//scanf,puts,printf not use
    int t;
    cin >> t;
    while (t--)
    {
        rep1(i,1,4)
            cin >> a[i],bo[i] = false;
        if (choose_num(1))
            cout <<"Yes"<<endl;
        else
            cout <<"No"<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/AWCXV/p/7626362.html