算法导论的作业,编程使得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]);
}
}