题目略
思路:
这个题从第一次接触到现在,理解已经上了很多个层次,中间的过程由于没有详细的记录,故略去,直接说说现在对这道题目的认识
题目要求从一堆物品中选出一些来塞入固定容量的背包从而使得背包的价值最大,首先我们先构想出最优的状态——排成一队的物品,依次选出几个放入背包中,假设我们一共选出了x个物品,那么0-1背包的核心代码的意思就是“一次扫全部,全部扫描一次的状态”。即对于第1...x个物品究竟选择谁好,这件事请对于外层for循环而言,每循环一次,就用相应自己的内层for循环干一遍这件事。理解了这点之后,就比较容易触类旁通了。
#include <iostream> #include <cstdio> #include <cstring> using namespace std; int main() { int n,w; int weight[107],value[107]; int f[10007]; int tm; while(~scanf("%d%d",&n,&w)) { tm = 0; memset(f,0,sizeof(f)); for(int i = 1;i <= n;i++) scanf("%d%d",&weight[i],&value[i]); for(int i = 1;i <= n;i++) for(int j = w;j >= weight[i];j--) f[j] = max(f[j],f[j-weight[i]]+value[i]); for(int i = 0;i <= w;i++) tm = f[i]>tm?f[i]:tm; printf("%d ",tm); } return 0; }