SRM397 CollectingMarbles

Maybe you don't know, but you are a fanatic of colored marbles. You want to collect them all, but you may not be able to carry them. You have numberOfBags bags, each of capacity bagCapacity grams. The i-th marble has a weight of marblesWeight[i] grams. You can go to the shop only once and you have enough money to buy all of the marbles. Return the largest number of marbles that you can carry home in the given bags.

题目和普通的背包有所不同,求的是所有组合中能拿走的最大个数。而且背包是复数个。

由于marblesWeight数组个数N<14,可以用组合计数枚举每一种组合情况。1~1<<13。分层求1到M个背包中拿走最多的个数比较困难,不如枚举出每一种个数需要的最小背包数量——事实上,两者是一个意思。

方程是dp[i|k] = min ( dp[k] + 1) i 要求能在一个背包里放下,k和i互相不重叠。

class CollectingMarbles
{
	int count ( int n )
	{
		int ret = 0;
		while ( n )
		{
			if ( n & 1 )
				ret ++;
			n >>= 1;
		}
		return ret;
	}
public:
	int mostMarbles ( vector 
  
   marblesWeights, int bagCapacity, int numberOfBags )
	{
		int N = marblesWeights.size ();
		int res = 0;
		int dp[1 << 13];
		int i, j;
		rpt ( i, 1 << N )
		dp[i] = MAX;
		dp[0] = 0;
		rpt ( i, 1 << N )
		{
			int sum = 0;
			rpt ( j, N )
			{
				if ( i & ( 1 << j ) )
					sum += marblesWeights[j];
			}
			if ( sum <= bagCapacity )
			{
				//printf ( "%d/n", sum );
				rpt ( j, 1 << N )
				{
					if ( !( i & j ) )
						dp[i | j] = min ( dp[i | j], dp[j] + 1 );
				}
			}
		}
		rpt ( i, 1 << N )
		if ( dp[i] <= numberOfBags )
			res = max ( res, count ( i ) );
		return res;
	}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值