现在的位置: 首页 > 综合 > 正文

SRM397 CollectingMarbles

2019年04月14日 ⁄ 综合 ⁄ 共 1006字 ⁄ 字号 评论关闭

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;
	}
};

抱歉!评论已关闭.