题目链接:http://poj.org/problem?id=3983
中文题,就不解释题意了。
类似之前的一篇博客,这里也不上解释了,直接上代码吧。
#include <iostream> #include <stdio.h> #include <string> using namespace std; char op[4]={'+','-','*','/'}; double calc(double a,int opnum,double b) { switch(op[opnum]) { case '+': return a+b; break; case '-': return a-b; break; case '*': return a*b; break; case '/': return a/b; break; } } bool calculator(int i, int j, int k, double a, double b, double c, double d) { if (calc(calc(a, i, b),j,calc(c, k, d)) - 24.0 == 0) { printf("(%.0lf%c%.0lf)%c(%.0lf%c%.0lf) ",a, op[i], b, op[j], c, op[k], d); return 1; } if (calc(calc(calc(a, i, b), j, c), k, d) - 24.0 == 0) { printf("((%.0lf%c%.0lf)%c%.0lf)%c%.0lf) ",a, op[i], b, op[j], c, op[k], d); return 1; } if (calc(calc(a, i, calc(b, j, c)), k, d) - 24.0 == 0) { printf("(%.0lf%c(%.0lf%c%.0lf))%c%.0lf) ",a, op[i], b, op[j], c, op[k], d); return 1; } if (calc(a, i, calc(calc(b, j, c), k, d)) - 24.0 == 0) { printf("%.0lf%c((%.0lf%c%.0lf)%c%.0lf) ",a, op[i], b, op[j], c, op[k], d); return 1; } if (calc(a, i, calc(b, j, calc(c, k, d))) == 24.0) { printf("%.0lf%c(%.0lf%c(%.0lf%c%.0lf)) ",a, op[i], b, op[j], c, op[k], d); return 1; } return 0; } int main() { double a,b,c,d; while (scanf("%lf %lf %lf %lf", &a, &b, &c, &d) != EOF) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { for (int k = 0; k < 4; k++) { if (calculator(i,j,k,a,b,c,d)==1) goto over; } } } over:continue; } return 0; }