poj 3983 快算24

题目来源:http://poj.org/problem?id=3983

因为共4个数,因此加括号的方式有如下几种情况:

(a oper b)oper(c oper d)

((a oper b) oper c) oper d)

(a oper (b oper c)) oper d

a oper ((b oper c) oper d)

a oper (b oper (c oper d))

表达式总共有5 * 4^3 = 320种情况,因此可以枚举出每一个表达式;

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>

using namespace std;


const double Threshold = 1e-6;

char operators[4] = {'+', '-', '*', '/' };

double Calculate(double a, int oper, double b)
{
    switch(operators[oper])
    {
    case '+':
        return a + b;
        break;
    case '-':
        return a - b;
        break;
    case '*':
        return a * b;
        break;
    case '/':
        return a / b;
        break;
    default:
        break;
    }
    return 0;
}

bool Calcu_Expression(double a, int i, double b, int j, double c, int k, double d)
{
    if(fabs(Calculate(Calculate(a, i, b), j, Calculate(c, k, d)) - 24.0) < Threshold)//(a oper b)oper(c oper d)
    {
        printf("(%.0lf%c%.0lf)%c(%.0lf%c%.0lf)\n", a, operators[i], b, operators[j], c, operators[k], d);
        return true;
    }
    if(fabs(Calculate(Calculate(Calculate(a, i, b), j, c), k, d) - 24.0) < Threshold)//((a oper b) oper c) oper d)
    {
        printf("((%.0lf%c%0.lf)%c%0.lf)%c%.0lf\n", a, operators[i], b, operators[j], c, operators[k], d);
        return true;
    }
    if(fabs(Calculate(Calculate(a, i, Calculate(b, j, c)), k, d) - 24.0) < Threshold)//(a oper (b oper c)) oper d
    {
        printf("(%0.lf%c(%0.lf%c%0.lf))%c%0.lf\n", a, operators[i], b, operators[j], c, operators[k], d);
        return true;
    }
    if(fabs(Calculate(a, i, Calculate(Calculate(b, i, c), k, d)) - 24.0) < Threshold)//a oper ((b oper c) oper d)
    {
        printf("%0.lf%c((%0.lf%c%0.lf)%c%0.lf)\n", a, operators[i], b, operators[j], c, operators[k], d);
        return  true;
    }
    if(fabs(Calculate(a, i, Calculate(b, j, Calculate(c, k, d))) - 24.0) < Threshold)//a oper (b oper (c oper d))
    {
        printf("%0.lf%c(%0.lf%c(%0.lf%c%0.lf))\n", a, operators[i], b, operators[j], c, operators[k], d);
        return true;
    }
    return false;
}

int main()
{
    double a, b, c, d;
    while(~scanf("%lf %lf %lf %lf", &a, &b, &c, &d))
    {
        for(int i = 0; i < 4; ++i)
        {
            for(int j = 0; j < 4; ++j)
            {
                for(int k = 0; k < 4; ++k)
                    if(Calcu_Expression(a, i, b, j, c, k, d))
                        goto Success;
            }
        }
        Success:
            continue ;
    }
    return 0;
}


你可能感兴趣的:(模拟)