hdu2844_多重揹包

Whuacmers use coins.They have coins of value A1,A2,A3...An Silverland dollar. One day Hibix opened purse and found there were some coins. He decided to buy a very nice watch in a nearby shop. He wanted to pay the exact price(without change) and he known the price would not more than m.But he didn't know the exact price of the watch.

You are to write a program which reads n,m,A1,A2,A3...An and C1,C2,C3...Cn corresponding to the number of Tony's coins of value A1,A2,A3...An then calculate how many prices(form 1 to m) Tony can pay use these coins.
 

Input
The input contains several test cases. The first line of each test case contains two integers n(1 ≤ n ≤ 100),m(m ≤ 100000).The second line contains 2n integers, denoting A1,A2,A3...An,C1,C2,C3...Cn (1 ≤ Ai ≤ 100000,1 ≤ Ci ≤ 1000). The last test case is followed by two zeros.
 

Output
For each test case output the answer on a single line.
 

Sample Input
3 10 1 2 4 2 1 1 2 5 1 4 2 1 0 0
 

Sample Output
8 4
很明顯的多重揹包的題目,很適合練手。我們只需要注意當物品的weight>揹包的Volume的時候這個就變成了完全揹包,如果小於的時候就把多重揹包轉變成二進制的01揹包,如15 可以用2 4 8 1進行表示 加快效率
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <iostream>
#include<cmath>
using namespace std;
long long dp[100005];
int n,m;
#define INF -1234567890
void onezeropack(int val,int w){
	for(int i=m;i>=w;i--){
		dp[i]=max(dp[i],dp[i-w]+val);
	}
}
void completepack(int val,int w){
	for(int i=val;i<=m;i++){
		dp[i]=max(dp[i],dp[i-w]+val);
	}
}
void multipack (int val,int w,int c){
	if(c*val>m){
		completepack(val,w);//價值與數目的總和大於了給出的限制 所以這一個循環把多重揹包看作完全揹包 
		return ;
	}
	else {
		int k=1;
		while(k<=c){
			onezeropack(val*k,w*k);//如果小於 則看作一個01揹包 進行二進制優化 把一個數拆分成多個數的累積 
			c-=k;
			k*=2;
		}//二進制優化處理
		onezeropack(c*val,c*w); 
	}
	return ;
}
int main(){
	while(scanf("%d%d",&n,&m)==2&&(n+m!=0)){
		int weight[105],c[105];
		for(int i=1;i<=n;i++){
			scanf("%d",&weight[i]);
		}
		for(int i=1;i<=n;i++){
			scanf("%d",&c[i]);
		}
		for(int i=0;i<=m;i++)dp[i]=INF;
		dp[0]=0;
		for(int i=1;i<=n;i++){
			multipack(weight[i],weight[i],c[i]);//第一個參數是價值(這題也是weight)第二個是weight 第三個是數量 
		}
		int ans=0;
		for(int i=1;i<=m;i++){
			if(dp[i]>0)ans++;
		}
		printf("%d\n",ans);
	}
}


發佈了35 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章