您的位置:首页 > 其它

背包问题模板

2016-08-07 20:28 211 查看
/*
背包问题模板
【若要求恰好装满,初始化时f[1...V] = -1(求最大)而f[0] = 0】
*/
#include <iostream>
#include <algorithm>
using namespace std;
const int M = 1000;
int c[M], w[M], nl[M];//c:费用 w:价值 n1:数量
int f[M];//f[与V有关],c和w[与n]有关
int v, V, V1;//V:容量 V1:容量2
//01背包
void ZeroOnePack(int c, int w){
for (int v = V; v >= c; v--)
f[v] = max(f[v], f[v - c] + w);
}
//完全背包
void CompletePack(int c, int w){
for (int v = c; v <= V; v++)
f[v] = max(f[v], f[v - c] + w);
}
//多重背包
void MultiplePack(int c, int w, int n1){
if (c * n1 >= V)
CompletePack(c, w);
else{
int k = 1;
while (k < n1){  //二进制拆分
ZeroOnePack(k*c, k*w);
n1 -= k;
k <<= 1;
}
ZeroOnePack(n1*c, n1*w);
}
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: