多重背包(二进制优化)

马上就要轻院校赛了,没时间了,下面是网上找的多重背包,感觉很好

void ZeroOnePack(int cost, int weight, int n) {
	for (int i = n; i >= cost; i--)
		dp[i] = max(dp[i], dp[i - cost] + weight);
}
void CompletePack(int cost, int weight, int n) {
	for (int i = cost; i <= n; i++)
		dp[i] = max(dp[i], dp[i - cost] + weight);
}
void MultiPack(int c[], int w[], int num[], int n, int m) {
	//c[]重量,w[]价值,n物品数,m容量,
	memset(dp, 0, sizeof(dp));
	for (int i = 1; i <= n; i++) {
		if (num[i] * c[i] > m)
			CompletePack(c[i], w[i], m);
		else {
			int k = 1;
			while (k < num[i]) {
				ZeroOnePack(k*c[i], k*w[i], m);
				num[i] -= k;
				k <<= 1;
			}
			ZeroOnePack(num[i] * c[i], num[i] * w[i], m);
		}
	}
}
poj1276是一道多重背包题 by wjqin

const int maxn = 125007;
int w[55], num[55];
int dp[maxn];
void ZeroOnePack(int c, int w, int v, int dp[]) {
	for (int j = c; j >= w; --j)
		dp[j] = max(dp[j], dp[j - w] + v);
}
void CompletePack(int c, int w, int v, int dp[]) {
	for (int j = w; j <= c; ++j)
		dp[j] = max(dp[j], dp[j - w] + v);
}
void multiPack(int n, int c, int w[], int num[], int dp[]) {
	fill(dp, dp + maxn, 0);
	for (int i = 1; i <= n; ++i) {
		if (num[i] * w[i] > c) {
			CompletePack(c, w[i], w[i], dp);
		}
		else {
			int k = 1;
			while (k < num[i]) {
				ZeroOnePack(c, k * w[i], k * w[i], dp);
				num[i] -= k;
				k <<= 1;				
			}
			ZeroOnePack(c, num[i] * w[i], num[i] * w[i], dp);
		}
	}
}

wa到不知道为啥子,memset(dp, 0,sizeof(dp));有时并未将dp数组中的值赋为0(可能与sizeof有关), fill()更靠谱些,

big event int hdu

你可能感兴趣的:(ACM-ICPC)