标签:
对于这种题用程序实现只能是穷举的思想,而做法各异,如下代码是利用符号的不断变化,利用4个数计算值,默认是4个数字a,b,c,d是按顺序计算的,即默认是加了括号的,即(((a op1 b)op2 c)op3 d)。而4个数字要组合顺序有A(4,4)=24种,很好理解,代码放在这里存档~
#include<iostream> using namespace std; /* (((aop[i]b)op[j]c)op[k]d) */ static char op[]={'+','-','*','/'}; int cal(int a,int b,int c,int d,int i,int j,int k) { int sum=0; if(i==0)sum=a+b; else if(i==1)sum=a-b; else if(i==2)sum=a*b; else if(i==3)sum=a/b; if(j==0)sum=sum+c; else if(j==1)sum-=c; else if(j==2)sum*=c; else if(j==3)sum/=c; if(k==0)sum+=d; else if(k==1)sum-=d; else if(k==2)sum*=d; else if(k==3)sum/=d; return sum; } bool Game24Points(int a, int b, int c, int d) { int i,j,k; for(i=0;i<4;i++) for(j=0;j<4;j++) for(k=0;k<4;k++) { if(cal(a,b,c,d,i,j,k)==24) return true; if(cal(a,b,d,c,i,j,k)==24)return true; if(cal(a,c,b,d,i,j,k)==24)return true; if(cal(a,c,d,b,i,j,k)==24)return true; if(cal(a,d,b,c,i,j,k)==24)return true; if(cal(a,d,c,b,i,j,k)==24)return true; if(cal(b,a,c,d,i,j,k)==24)return true; if(cal(b,a,d,c,i,j,k)==24)return true; if(cal(b,c,a,d,i,j,k)==24)return true; if(cal(b,c,d,a,i,j,k)==24)return true; if(cal(b,d,a,c,i,j,k)==24)return true; if(cal(b,d,c,a,i,j,k)==24)return true; if(cal(c,a,b,d,i,j,k)==24)return true; if(cal(c,a,d,b,i,j,k)==24)return true; if(cal(c,b,a,d,i,j,k)==24)return true; if(cal(c,b,d,a,i,j,k)==24)return true; if(cal(c,d,a,b,i,j,k)==24)return true; if(cal(c,d,b,a,i,j,k)==24)return true; if(cal(d,a,b,c,i,j,k)==24)return true; if(cal(d,a,c,b,i,j,k)==24)return true; if(cal(d,b,a,c,i,j,k)==24)return true; if(cal(d,b,c,a,i,j,k)==24)return true; if(cal(d,c,a,b,i,j,k)==24)return true; if(cal(d,c,b,a,i,j,k)==24)return true; } return false; } int main() { if(Game24Points(7, 2, 1, 10) == true) cout<<"true"<<endl; if(Game24Points(1, 2, 3, 4) == true)cout<<"true"<<endl; if(Game24Points(7, 7, 7, 7) == false)cout<<"true"<<endl; return 0; }
标签:
原文地址:http://blog.csdn.net/wljwsj/article/details/45478709