启发式搜索练习(更新中)

介绍下概念:简单来说,启发式搜索就是对取和不取都做分析,从中选取更优解(或删去无效解)

例题:P1048 采药

所有的启发式搜索都会有一个估价函数。下面是这一题的估价函数。

const int N = 105;
struct Node {
  int a, b;  // a代表时间,b代表价值
  double f;
} node[N];

int f(int t, int v) {
  int tot = 0;
  for (int i = 1; t + i <= n; i++)
    if (v >= node[t + i].a) {
      v -= node[t + i].a;
      tot += node[t + i].b;
    } else
      return (int)(tot + v * node[t + i].f);
  return tot;
}

那么估价函数是什么呢?我们都知道,背包问题的最基础的思路是O(2^n)。一个状态有两种决策,分别是取和不取,那么,我们在取的时候判断一下是不是超过了体积,在不取的时候判断一下,如果,我不取这个,那么,剩下的所有的价值+现有的价值有没有大于我所找到的目前的最优解,如果没有,不取是没有意义的。听不懂?没关系。我们先上核心代码。

void work(int t, int p, int v) {
    ans = max(ans, v);
    if (t > n) return;
    if (f(t, p) + v > ans) work(t + 1, p, v);
    if (node[t].a <= p) work(t + 1, p - node[t].a, v + node[t].b);
}

假设,我现在的最优解是2,如果我不取这个物品,所能得到的估价比这个小,说明不取是没有意义的,因为就算你剩下的全部取了都不是最优解。那么,估价有没有可能估小了呢?不可能。

bool operator <(const Node &a,const Node &b)
{
	return a.f>b.f;
}
sort(node+1,node+1+n);

上面这段代码就保证了不可能估小。以及,我们在估价时,不管它到底可不可以放进去,只有背包有空间,就放,而放的价值就是单位价值:

	node[i].f=1.0 * node[i].b / node[i].a

好的,我们现在就放出完整代码。

#include <algorithm>
#include <iostream>
// heuristic-search 启发式搜索
using namespace std;
const int N = 105;
int m, t, ans;
struct Node {
	int time, value;
	double f;
} node[N];

bool operator<(Node p, Node q) { return p.f > q.f; };

// f 估价函数 time限制下,不取idx,去i[dx+1,m]的剩余总价值,
int f(int idx, int time) {
	int tot = 0;
	for (int i = 1; idx + i <= m; i++)
		if (time >= node[idx + i].time) {
			time -= node[idx + i].time;
			tot += node[idx + i].value;
		} else
			return (int) (tot + time * node[idx + i].f);
	return tot;
}

void dfs(int idx, int time, int v) {
	ans = max(ans, v);
	if (idx > m) return;// 可行性剪枝
	if (f(idx, time) + v > ans) // 不取,最优性剪枝. 解释: 意味着我不取得情况下,后续能取最大价值能不能大于目前最大得价值!
		dfs(idx + 1, time, v);
	if (node[idx].time <= time) // 可行性剪枝
		dfs(idx + 1, time - node[idx].time, v + node[idx].value);
}

int main() {
	cin >> t >> m;
	for (int i = 1; i <= m; i++) {
		cin >> node[i].time >> node[i].value;
		node[i].f = 1.0 * node[i].value / node[i].time;
	}
	sort(node + 1, node + m + 1);
	dfs(1, t, 0);
	cout << ans << endl;
	return 0;
}
原文地址:https://www.cnblogs.com/RioTian/p/13304064.html