poj3983 (24点)
给出4个数,只能添加+-*/或者()使得结果为24。
思路:枚举,一共5*3^4.
#include <iostream> using namespace std; double a,b,c,d; double f(double a,double b,int op) { if(1 == op) return a+b; if(2 == op) return a-b; if(3 == op) return a*b; return a/b; } //type表示加括号的方式,一共5种 bool caculate(int p1,int p2,int p3,int type) { double ans=0.0; if(1 == type) ans=f(f(f(a,b,p1),c,p2),d,p3); else if(2 == type) ans=f(f(a,b,p1),f(c,d,p3),p2); else if(3 == type) ans=f(a,f(b,f(c,d,p3),p2),p1); else if(4 == type) ans=f(f(a,f(b,c,p2),p1),d,p3); else ans=f(a,f(f(b,c,p2),d,p3),p1); if(24.0 == ans) return true; return false; } char getOp(int t) { if(1 == t) return '+'; if(2 == t) return '-'; if(3 == t) return '*'; return '/'; } void output(int op1,int op2,int op3,int type) { char p1,p2,p3; p1=getOp(op1); p2=getOp(op2); p3=getOp(op3); if(1 == type) printf("((%.0lf%c%.0lf)%c%.0lf)%c%.0lf\n",a,p1,b,p2,c,p3,d); else if(2 == type) printf("(%.0lf%c%.0lf)%c(%.0lf%c%.0lf)\n",a,p1,b,p2,c,p3,d); else if(3 == type) printf("%.0lf%c(%.0lf%c(%.0lf%c%.0lf))\n",a,p1,b,p2,c,p3,d); else if(4 == type) printf("(%.0lf%c(%.0lf%c%.0lf))%c%.0lf\n",a,p1,b,p2,c,p3,d); else printf("%.0lf%c((%.0lf%c%.0lf)%c%.0lf)\n",a,p1,b,p2,c,p3,d); } int main() { while(scanf("%lf%lf%lf%lf",&a,&b,&c,&d)!=EOF) { bool found=true; for(int i=1;i<=4&&found;++i) { for(int j=1;j<=4&&found;++j) { for(int k=1;k<=4&&found;++k) { for(int type=1;type<=5&&found;++type) { if(caculate(i,j,k,type)) { output(i,j,k,type); found=false; } } } } } } return 0; }