HDOJ 1059 Dividing

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1059

 

题目大意:有6种marbles,其价值分别为1…6,每种marbles有一定的数量,请问是否可以将这些marbles分成两部分,每部分的价值总量相等,即等于所有marbles的总价值的一半。

 

题意分析:我们可以考虑用01背包或者多重背包的问题解决。至于01背包和多重背包问题,可参考:http://blog.youkuaiyun.com/dzyhenry/article/details/8883528

注意本题中的c[i]与w[i]是相同的,即消耗和价值是相同的,所以如果f[v]等于v,则背包必然是恰好填满的


多重背包:

#include<stdio.h>
#include<string.h>

int marbles[7];
int dp[60001];
int totalV;
int halfV;

void zeroOnePack(int cost, int weight)
{
	int i;
	for(i=halfV; i>=cost; i--){
		if(dp[i] < dp[i-cost]+weight){
			dp[i] = dp[i-cost]+weight;
		}
	}
}

void completePack(int cost, int weight)
{
	int i;
	for(i=cost; i<=halfV; i++){
		if(dp[i] < dp[i-cost]+weight){
			dp[i] = dp[i-cost]+weight;
		}
	}
}

void multplePack(int cost, int weight, int amount)
{
	int i, k;
	if(amount*cost >= halfV){
		completePack(cost, weight);
	}
	else{
		for(k=1; k<amount; k<<=1){
			zeroOnePack(cost*k, weight*k);
			amount -= k;
		}
		zeroOnePack(cost*amount, weight*amount);
	}
}

int main()
{
	int n, i, j, k, t;

	t = 1;
	while(scanf("%d", &marbles[1]) != EOF){
	
		
		totalV = marbles[1];
		for(i=2; i<=6; i++){
			scanf("%d", &marbles[i]);
			totalV += marbles[i]*i;
		}
		
		if(!totalV)
			break;
		
		if(totalV & 1){
			printf("Collection #%d:\n", t++);
			printf("Can't be divided.\n\n");
			continue;
		}
		memset(dp, 0, sizeof(dp));
		
		halfV = totalV / 2;
		for(i=1; i<=6; i++){
			multplePack(i, i, marbles[i]);
		}
		
		if(dp[halfV] == halfV){
			printf("Collection #%d:\n", t++);
			printf("Can be divided.\n\n");
		}
		else{
			printf("Collection #%d:\n", t++);
			printf("Can't be divided.\n\n");
		}
	}
	return 0;
}


01背包:

#include<stdio.h>
#include<string.h>

int marbles[7];
int dp[60000];
int totalV;
int halfV;

int main()
{
	int n, i, j, k, t;

	t = 1;
	while(scanf("%d", &marbles[1]) != EOF){
	
		memset(dp, 0, sizeof(dp));
		totalV = marbles[1];
		for(i=2; i<=6; i++){
			scanf("%d", &marbles[i]);
			totalV += marbles[i]*i;
		}
		
		if(!totalV)
			break;
		
		if(totalV & 1){
			printf("Collection #%d:\n", t++);
			printf("Can't be divided.\n\n");
			continue;
		}

		halfV = totalV / 2;
		for(i=0; i<=marbles[1]&&i<=halfV; i++)
			dp[i] = 1;
		
		for(i=2; i<=6; i++){
			if(!marbles[i])
				continue;
			for(j=halfV; j>=0; j--){
				if(dp[j] == 0)
					continue;
				for(k=1; k<=marbles[i]&&k*i+j<=halfV; k++){
					if(dp[k*i+j])
						break;
					dp[k*i+j] = 1;
				}
				
			}
		}

		if(dp[halfV]){
			printf("Collection #%d:\n", t++);
			printf("Can be divided.\n\n");
		}
		else{
			printf("Collection #%d:\n", t++);
			printf("Can't be divided.\n\n");
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值