码迷,mamicode.com
首页 > 其他好文 > 详细

背包问题模板

时间:2016-08-07 21:30:03      阅读:83      评论:0      收藏:0      [点我收藏+]

标签:

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

  

背包问题模板

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!