算法导论的作业,编程使得8个8通过加减乘除得到1000。该题类似24点,但数据规模远大于24点的算法。具体思路参考24点的算法,在编程之美中有提到过。
深搜,然后用map 进行对2个操作数的判重进行剪枝,但是该方法仍然会得到大量的重复算式,想了想用set进行筛选重复的expression,虽然稍微影响效率,但是也没事,最终能在20秒左右搜出结果。
代码:
/*
** 8个8 加减乘除得到 1000
** Jet-Muffin
*/
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <map>
#include <set>
using namespace std;
const double EPS = 1e-6;
const int NUM = 8;
const int RES = 1000;
double A[NUM];
string res_str[NUM];
set<string> ans;
set<string>::iterator it;
int times = 0;
bool dfs(int n)
{
// 退出条件
if (n==1)
{
if (fabs(A[0]-RES)<EPS)
{
// cout << res_str[0] << endl;
ans.insert(res_str[0]);
}
}
double a, b;
string expa, exp

这篇博客介绍了如何通过深度搜索配合剪枝策略来解决算法问题,即利用8个8通过加减乘除得到1000。博主提到了该问题类似于24点游戏,但规模更大。他们使用了地图进行重复操作数的判重剪枝,并用集合来过滤重复的表达式,虽然略微影响效率,但能确保在20秒内找到解决方案。
最低0.47元/天 解锁文章
1832

被折叠的 条评论
为什么被折叠?



