POJ1014 :Dividing(多重背包) 二进制优化

Marsha and Bill own a collection of marbles. They want to split the collection among themselves so that both receive an equal share of the marbles. This would be easy if all the marbles had the same value, because then they could just split the collection in half. But unfortunately, some of the marbles are larger, or more beautiful than others. So, Marsha and Bill start by assigning a value, a natural number between one and six, to each marble. Now they want to divide the marbles so that each of them gets the same total value. Unfortunately, they realize that it might be impossible to divide the marbles in this way (even if the total value of all marbles is even). For example, if there are one marble of value 1, one of value 3 and two of value 4, then they cannot be split into sets of equal value. So, they ask you to write a program that checks whether there is a fair partition of the marbles.
Input
Each line in the input file describes one collection of marbles to be divided. The lines contain six non-negative integers n1 , . . . , n6 , where ni is the number of marbles of value i. So, the example from above would be described by the input-line "1 0 1 2 0 0". The maximum total number of marbles will be 20000. 
The last line of the input file will be "0 0 0 0 0 0"; do not process this line.
Output
For each collection, output "Collection #k:", where k is the number of the test case, and then either "Can be divided." or "Can't be divided.". 
Output a blank line after each test case.
Sample Input
1 0 1 2 0 0 
1 0 0 0 1 1 
0 0 0 0 0 0 
Sample Output
Collection #1:
Can't be divided.

Collection #2:
Can be divided.


这个题目是一个多重背包,题目的意思是,每行6个数,分别代表弹珠的数量,然后一到六就是弹珠的价值,然后看看能不能平均吧弹珠分成价值相等的两份。。

如果价值的和是奇数的话,就一定不能分成两份,如果是偶数的话,就可以讨论一下。

由于每个弹珠的数量大,而且把价值乘起来的话,那就更大了,

一般的多重背包,肯定就会超时。

这时就要用 二进制优化一下。


可以这样想。

多重背包,一个弹珠有很多个,把同一种弹珠分成价值不同的好多份,再进行01背包,每次只能取一个,

一个算一份

两个算一份

四个算一份

八个算一份

…………

有可能不会分完,最后还会剩下一点,不能忘了。


#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
	int a[10],sum,tt;
	bool f[100000];  //用布尔型比较好一点。
	sum = 0;
	tt = 1;
	for (int i = 1; i <= 6; i++)
	{
		scanf("%d",&a[i]);
		sum += a[i] * i;
	}
	while(sum)
	{
		printf("Collection #%d:\n",tt++);
		if (sum & 1 == 1)
		{
			printf("Can't be divided.\n\n");
		} else
		{
			memset(f,0,sizeof(f));
			f[0] = 1;
			sum /= 2; // 价值。
			for (int i = 1; i <= 6; i++)
			{
				if (!a[i])
				continue;
				for (int j = 1; j <= a[i]; j *= 2) //二进制优化,
				{
					for (int k = sum; k >= j*i; k--)
						if (f[k - i*j ]) f[k] = 1;
					a[i] -= j; //分完之后,再减去。	
				}
				if (a[i]) //还剩多少个弹珠。
				{
					for (int k = sum; k >= a[i]*i; k--)
						if (f[k - a[i]*i]) f[k] = 1;
				}
			}
			if (f[sum]) printf("Can be divided.\n\n"); else
				printf("Can't be divided.\n\n");
		}
		sum = 0;
		for(int i = 1; i <= 6; i++)
		{
			scanf("%d",&a[i]);
			sum += a[i] * i;
		}
	}
	return 0;
}


猜你喜欢

转载自blog.csdn.net/kidsummer/article/details/79327778