#include<iostream>
#include<vector>
#include<iomanip>
using namespace std;
enum { WHITE, GRAY };
enum { PLUS = 1, MINUS, MULTIPLY, DIVIDE };
vector<double> a = { 7,2,2,12,3 };
vector<int> Color;
const int k = (int)a.size();
const double m = 125;
vector<double>Rec;//记录
bool Search(int _size=k,int unused=k);//_size记录a数组实际大小,unused记录还有多少个元素未使用
inline double Calculate(double one,int Symbol,double two);
inline char Translate(int Symbol);
int main()
{
for (int i = 0; i < k; i++)
Color.push_back(WHITE);
if (!Search())
cout << "无解" << endl;
}
bool Search(int _size, int unused)
{
if (unused == 1)//只有一个数没有使用,这个数就是经过多次运算后的结果
{
int i = 0;
while (Color[i] == GRAY)++i;//没有使用的数在Color数组中标志是WHITE
if (a[i] == m)//得到最终结果
{
for (int j = 0; j < (int)Rec.size(); j += 3)//以三个为一组
{
cout << setw(3) << Rec[j] << setw(3) << Translate((int)Rec[j + 1]) << setw(3) << Rec[j + 2]
<< setw(3) << '=' << setw(3) << Calculate(Rec[j], (int)Rec[j + 1], Rec[j + 2]) << endl;
}
return true;
}
else//非最终结果
return false;
}
else
{
for (int i = 0; i < _size; i++)//取a[i]作为第一个参与运算的数字
{
for (int j = 0; j < _size; j++)//取a[j]作为第二个参与运算的数字
{
if ((i != j)&&(Color[i]==WHITE)&&(Color[j]==WHITE))
//i和j均是没有参与过运算的数
{
Color[i] = GRAY;
Color[j] = GRAY;
Rec.push_back(a[i]);
for (int Symbol = 1; Symbol <= 4; Symbol++)
//选择运算符
{
if ((Symbol != 4) || (a[j] != 0))
//a[j]为0时不能使用除法
{
Rec.push_back(Symbol);
Rec.push_back(a[j]);
a.push_back(Calculate(a[i], Symbol, a[j]));
Color.push_back(WHITE);
//成功需要退出
if (Search(_size + 1, unused - 1) == true)
return true;
else
{
//失败则回溯
Color.pop_back();
a.pop_back();
Rec.pop_back();
Rec.pop_back();
}
}
}
Rec.pop_back();
Color[j] = WHITE;
Color[i] = WHITE;
}
}
}
return false;
}
}
double Calculate( double one,int Symbol, double two)
{
if (Symbol == PLUS)
return one + two;
else if (Symbol == MINUS)
return one - two;
else if (Symbol == MULTIPLY)
return one * two;
else
return one / two;//two不能为0
}
char Translate(int Symbol)
{
if (Symbol == PLUS)
return '+';
else if (Symbol == MINUS)
return '-';
else if (Symbol == MULTIPLY)
return '*';
else
return '/';
}
10-08
3314
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-31
452
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)