背包问题模板

/*
背包问题模板
【若要求恰好装满,初始化时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);
	}
}

  

原文地址:https://www.cnblogs.com/td15980891505/p/5747130.html