题解 P1048 【采药】
这道题的解法很多,大部分是动态规划和记忆化搜索,但是如果T一旦很大的话,动态规划和记忆化搜索会被卡掉。那我们有没有别的方法呢?是有的。
下面隆重介绍:
启发式搜索
启发式搜索是在暴力DFS基础上进行剪枝的搜索。你可能会说,不就是剪了一点枝吗,会快很多吗?答案是会。
我们先说一下,所有的启发式搜索都会有一个估价函数。下面是这一题的估价函数。
struct node
{
int c,v;
double cost;
};
const int N=10000;
node a[N+5];
inline int f(int t,int v)
{
int tot=0;
for(int i=1;t+i<=n;i++)
{
if(v>=a[t+i].c)
{
v-=a[t+i].c;
tot+=a[t+i].v;
}
else return (int) (tot+v*a[t+i].cost);
}
return tot;
}
那么估价函数是什么呢?我们都知道,背包问题的最基础的思路是O(2^n)。一个状态有两种决策,分别是取和不取,那么,我们在取的时候判断一下是不是超过了体积,在不取的时候判断一下,如果,我不取这个,那么,剩下的所有的价值+现有的价值有没有大于我所找到的目前的最优解,如果没有,不取是没有意义的。听不懂?没关系。我们先上核心代码。
void DFS(int now,int cv,int cp)
{
ans=code::max(ans,cp);
if(now>n) {return;}
if(f(now,cv)+cp>ans) DFS(now+1,cv,cp);
if(cv-a[now].c>=0) DFS(now+1,cv-a[now].c,cp+a[now].v);
}
假设,我现在的最优解是2,如果我不取这个物品,所能得到的估价比这个小,说明不取是没有意义的,因为就算你剩下的全部取了都不是最优解。那么,估价有没有可能估小了呢?不可能。
bool operator <(const node &a,const node &b)
{
return a.cost>b.cost;
}
sort(a+1,a+1+n);
上面这段代码就保证了不可能估小。以及,我们在估价时,不管它到底可不可以放进去,只有背包有空间,就放,而放的价值就是单位价值:
a[i].cost=1.0*a[i].v/a[i].c
好的,我们现在就放出完整代码。
(本题思路来自我的老师宋力强,代码均由本人实现)
#include <algorithm>
#include <cctype>
#include <stdio.h>
int n, tot, ans;
struct node
{
int c, v;
double cost;
};
using namespace std;
const int N = 10000;
node a[N + 5];
int read() /*快读大法吼啊!*/
{
int x = 0;short w = 0;char ch = 0;
while (!isdigit(ch)){w |= ch == '-';ch = getchar();}
while (isdigit(ch)){x = (x << 3) + (x << 1) + (ch ^ 48);ch = getchar();}
return w ? -x : x;
}
inline int f(int t, int v) //估价函数,解释见上。
{
int tot = 0;
for (int i = 1; t + i <= n; i++)
{
if (v >= a[t + i].c)
{
v -= a[t + i].c;
tot += a[t + i].v;
}
else
return (int)(tot + v * a[t + i].cost);
}
return tot;
}
bool operator<(const node &a, const node &b)
{
return a.cost > b.cost;
} /*等价于
bool cmp(node a,node b)
{
return a.cost>b.cost;
}
*/
void DFS(int now, int cv, int cp)
{
ans = max(ans, cp);
if (now > n)
{
return;
}
if (f(now, cv) + cp > ans)
DFS(now + 1, cv, cp);
if (cv - a[now].c >= 0)
DFS(now + 1, cv - a[now].c, cp + a[now].v);
}
int main()
{
tot = read(), n = read();
for (int i = 1; i <= n; i++)
{
a[i].c = read(), a[i].v = read();
a[i].cost = 1.0 * a[i].v / a[i].c;
}
sort(a + 1, a + 1 + n);
DFS(0, tot, 0);
printf("%d", ans);
return 0;
}
update:2020/5/2 将对新手不友好的语法改成了最朴素的写法