Hdu 1059 Dividing -- 多重背包

/*
	http://acm.hdu.edu.cn/showproblem.php?pid=1059  Dividing
	多重背包, 六种质量(1,2,3,4,5,6)的大理石,每种n[i]长,是否能分割为等质量的两份大理石,因为格式问题纠结死了
*/

#include <cstdio>
#include <iostream>
#include <string>
#include <cstring>
#define CLR(c,v) (memset(c,v,sizeof(c)))
using namespace std;

const int INF =   1<<30 ;
const int inf = -(1<<30);
const int M   = 21e4 + 10; // 21万

int n[10]; // 物品的个数
int dp[M];

void CompletePack(int cost , int value, int max_cost){
	for (int i = cost ; i <= max_cost ; i++){
		if(dp[i] < dp[i-cost] + value){
			dp[i] = dp[i-cost] + value;
		}
	}
}

void ZeroOnePack(int cost ,int value, int max_cost){
	for (int i = max_cost ; i >= cost ; i--){
		if (dp[i] < dp[i-cost] + value){
			dp[i] = dp[i-cost] + value;
		}
	}
}

void MultiplePack(int cost ,int value,int amount, int max_cost){
	if (max_cost < cost*amount){ // 如果总数过多
		CompletePack(cost , value , max_cost);
	}else{
		for (int k = 1 ; k <= amount ; k <<= 1 ){ // 二进制优化, 注意k <<= 1 总是忘记等号
			if (k*cost <= max_cost){
				ZeroOnePack(cost*k , value*k ,max_cost);
				amount -= k;
			}
		}
		ZeroOnePack(cost*amount , value*amount , max_cost); // 剩余
	}
}

int main()
{
	//freopen("in.txt","r",stdin);
	int Ncase = 0;
	while(cin >> n[0] >> n[1] >> n[2] >> n[3] >> n[4] >> n[5] && (n[0]||n[1]||n[2]||n[3]||n[4]||n[5]) ){
		CLR(dp,0);
		int sum = 0;
		for (int i = 1 ; i <= 6 ; i++){
			sum += n[i-1] * i; 
		}
		if (sum & 1){
			printf("Collection #%d:\nCan't be divided.\n\n",++Ncase);continue;
		}else{
			for (int i = 1 ; i <= 6 ; i++){
				MultiplePack(i , i , n[i-1] , sum >> 1);
			}
		}
		if (sum >> 1 == dp[sum >> 1]){
			printf("Collection #%d:\nCan be divided.\n\n",++Ncase);
		}else{
			printf("Collection #%d:\nCan't be divided.\n\n",++Ncase);
		}
	}
	return 0;
}

你可能感兴趣的:(C++)