\(24\) 点求解器,输出任意一组解。
#include <bits/stdc++.h>
using namespace std;
#define to_st to_string
#define in push_back
typedef double db;
typedef string st;
vector<pair<db,st>>Number;
int A,B,C,D;
bool Out;
void Output(){Out=true;puts("Possble!");cout<<Number[0].second<<"=24\n";}
void DFS(int step);
void Add(db A,st AA){Number.clear();Number.in({A,AA});}
void Add(db A,db B,st AA,st BB){Number.clear();Number.in({A,AA});Number.in({B,BB});}
void Add(db A,db B,db C,st AA,st BB,st CC){Number.clear();Number.in({A,AA});Number.in({B,BB});Number.in({C,CC});}
void Add(db A,db B,db C,db D,st AA,st BB,st CC,st DD){Number.clear();Number.in({A,AA});Number.in({B,BB});Number.in({C,CC});Number.in({D,DD});}
st Text(st A,char c,st B){
return '('+A+c+B+')';
}
void Calc(db A,db B,st AA,st BB){
Add(A+B,Text(AA,'+',BB));DFS(1);
Add(A-B,Text(AA,'-',BB));DFS(1);
Add(A*B,Text(AA,'*',BB));DFS(1);
if(B!=0){Add(A/B,Text(AA,'/',BB));DFS(1);}
}
void Calc(db A,db B,db C,st AA,st BB,st CC){
Add(A+B,C,Text(AA,'+',BB),CC);DFS(2);
Add(A-B,C,Text(AA,'-',BB),CC);DFS(2);
Add(A*B,C,Text(AA,'*',BB),CC);DFS(2);
if(B!=0){Add(A/B,C,Text(AA,'/',BB),CC);DFS(2);}
}
void Calc(db A,db B,db C,db D,st AA,st BB,st CC,st DD){
Add(A+B,C,D,Text(AA,'+',BB),CC,DD);DFS(3);
Add(A-B,C,D,Text(AA,'-',BB),CC,DD);DFS(3);
Add(A*B,C,D,Text(AA,'*',BB),CC,DD);DFS(3);
if(B!=0){Add(A/B,C,D,Text(AA,'/',BB),CC,DD);DFS(3);}
}
void DFS(int step){
if(Out) return;
if(step==1 and 23.9<Number[0].first and Number[0].first<24.1){
Output();
}else{
if(step==2){
db A=Number[0].first;
db B=Number[1].first;
st AA=Number[0].second;
st BB=Number[1].second;
Calc(A,B,AA,BB);
Calc(B,A,BB,AA);
}else if(step==3){
db A=Number[0].first;
db B=Number[1].first;
db C=Number[2].first;
st AA=Number[0].second;
st BB=Number[1].second;
st CC=Number[2].second;
Calc(A,B,C,AA,BB,CC);Calc(A,C,B,AA,CC,BB);
Calc(B,A,C,BB,AA,CC);Calc(B,C,A,BB,CC,AA);
Calc(C,A,B,CC,AA,BB);Calc(C,B,A,CC,BB,AA);
}else if(step==4){
db A=Number[0].first;
db B=Number[1].first;
db C=Number[2].first;
db D=Number[3].first;
st AA=Number[0].second;
st BB=Number[1].second;
st CC=Number[2].second;
st DD=Number[3].second;
Calc(A,B,C,D,AA,BB,CC,DD);Calc(A,C,B,D,AA,CC,BB,DD);Calc(A,D,B,C,AA,DD,BB,CC);
Calc(B,A,C,D,BB,AA,CC,DD);Calc(B,C,A,D,BB,CC,AA,DD);Calc(B,D,A,C,BB,DD,AA,CC);
Calc(C,A,B,D,CC,AA,BB,DD);Calc(C,B,A,D,CC,BB,AA,DD);Calc(C,D,A,B,CC,DD,AA,BB);
Calc(D,A,B,C,DD,AA,BB,CC);Calc(D,B,A,C,DD,BB,AA,CC);Calc(D,C,A,B,DD,CC,AA,BB);
}
}
}
void Main()
{
srand(time(0));
printf(">>> ");
scanf("%d%d%d%d",&A,&B,&C,&D);
Add(A,B,C,D,to_st(A),to_st(B),to_st(C),to_st(D));
Out=false;
DFS(4);
if(!Out){
puts("Impossble...QwQ");
}puts("");
}
int main()
{
while(true){
Main();
}
return 0;
}
标签:24,puts,求解,d%,st,Out
From: https://www.cnblogs.com/Sundar-2022/p/18139450