Have to say, personally I think that a lot of bigwigs want to program complex, so the amount of code is very long, but in fact, this problem does not have to be so complicated. . .
Could be considered a \ (DFS \) maintains a state \ (f (n) [a_1 , a_2 ...... a_n] \)
Next we enumerate violent match the two programs for each \ (A [I] \) , \ (A [J] \) larger value as long as the calculated value and a smaller number of two further analog arithmetic operation can be.
As mentioned in the comments section of the anti-reflection and anti besides actually having to consider, imagine every time we subtract the smaller value from the larger value, the larger value in addition to a small value, it is impossible for big or small decrease in addition to the small large.
For \ (A [I] \) , \ (a [j] \) match the two, may be the result of their operation into the \ (A [I] \) , and \ (a [j] \) can deposit \ (a [n] \) amount. It means simply scroll array of friends ~
This status is then compressed into \ (F (n--. 1) [A_1, A_2 ....... 1-n-A_ {}] \) , continue \ (DFS \) .
For the boundary processing, i.e., when the \ (n = 1 \) when the state becomes \ (F (. 1) [A_1] \) , \ (A_1 \) is the final result. If \ (a_1 = 24 \) illustrates the establishment of the maintenance process in each calculation \ (ok \) a.
#include<bits/stdc++.h>
using namespace std;
int num[10],f[20];
char ch[10];
bool Game(int n){
if(n==1){//边界
if(num[1]==24)return true;//判结果
else return false;
}
for(int i=1;i<=n;i++){
for(int j=i+1;j<=n;j++){//两两匹配,即可模拟所有可能
int ti=num[i],tj=num[j];//保留原结果
int a=max(ti,tj);
int b=min(ti,tj);//取较大较小值
int t=4-n;
num[j]=num[n];//压缩数组
//初始化
f[t*3+1]=a;
f[t*3+2]=b;
f[t*3+3]=a+b;
ch[t+1]='+';//记录运算过程
num[i]=a+b;//做加法
if(Game(n-1))return true;//DFS
f[t*3+1]=a;
f[t*3+2]=b;
f[t*3+3]=a-b;
ch[t+1]='-';//记录运算过程
num[i]=a-b;//做减法
if(Game(n-1))return true;//DFS
f[t*3+1]=a;
f[t*3+2]=b;
f[t*3+3]=a*b;
ch[t+1]='*';//记录运算过程
num[i]=a*b;//做乘法
if(Game(n-1))return true;//DFS
if(b!=0&&a%b==0){//判断是否除的尽
if(a/b>=1){
f[t*3+1]=a;
f[t*3+2]=b;
f[t*3+3]=a/b;
ch[t+1]='/';//记录运算过程
num[i]=a/b;//做除法
if(Game(n-1))return true;//DFS
}
}
num[i]=ti;
num[j]=tj;//答案错误还原之前结果
}
}
return false;
}
int main(){
for(int i=1;i<=4;i++){
cin>>num[i];
}
if(Game(4)){
cout<<f[1]<<ch[1]<<f[2]<<'='<<f[3]<<endl;
cout<<f[4]<<ch[2]<<f[5]<<'='<<f[6]<<endl;
cout<<f[7]<<ch[3]<<f[8]<<'='<<f[9]<<endl;//暴力输出
}else{
cout<<"No answer!"<<endl;
}
return 0;
}