本帖最后由 高山 于 2022-12-4 19:11 编辑
这个要求对算法太有难度了,我曾经研究一段时间24点算法,也写过一些程度,但的确没有找到完美的算法,难度有两点
1、算法里面可能会出现浮点,如对4个数算24,3 3 8 8 唯一的解是((3/8-3)/8),因为C++不支持分数运算,所以3/8要用浮点,这个会影响程序执行效率。
2、运算优先级,这个我没有完全解决,如我的程序,对3 3 8 8算24,结果为(((3/8)-3)/8),我也曾经写过专门优化()的程序,但过于复杂。
以下是我写的参考,只是对8个数,5秒我的程序做不到。(希望能一起探讨下)
#include <cmath>
#include <iostream>
#include <string>
using namespace std;
//因为有除,所以要用浮点
#define PRECISION 1E-6
//最多8个数
#define MAX_COUNT_OF_NUMBER 8
double number[MAX_COUNT_OF_NUMBER];
string expression[MAX_COUNT_OF_NUMBER];
int Search(int n, int r)
{
int i, j;
double a, b;
string expa, expb;
if (n == 1)
{
if (fabs(number[0] - r) < PRECISION)
{
cout << expression[0] << endl;
return 1;
}
else
return 0;
}
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
a = number[i];
b = number[j];
number[j] = number[n - 1];
expa = expression[i];
expb = expression[j];
expression[j] = expression[n - 1];
expression[i] = "(" + expa + "+" + expb + ")";
number[i] = a + b;
if (Search(n - 1, r))
return 1;
expression[i] = "(" + expa + "-" + expb + ")";
number[i] = a - b;
if (Search(n - 1, r))
return 1;
expression[i] = "(" + expa + "-" + expb + ")";
number[i] = b - a;
if (Search(n - 1, r))
return 1;
expression[i] = "(" + expa + "*" + expb + ")";
number[i] = a * b;
if (Search(n - 1, r))
return 1;
if (b != 0)
{
expression[i] = "(" + expa + "/" + expb + ")";
number[i] = a / b;
if (Search(n - 1, r))
return 1;
}
if (a != 0)
{
expression[i] = "(" + expa + "/" + expb + ")";
number[i] = b / a;
if (Search(n - 1, r))
return 1;
}
number[i] = a;
number[j] = b;
expression[i] = expa;
expression[j] = expb;
}
}
return 0;
}
int main()
{
int i, x;
int n, m;
cin >> n >> m;
for (i = 0; i < n; i++)
{
cin >> x;
number[i] = x;
expression[i] = to_string(x);
}
if (!Search(n, m))
cout << "No" << endl;
}
你知道本程序来自哪里
高小山不容易,望设最佳 |