Dividing
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 73834 Accepted: 19305
Description
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.
Source
Mid-Central European Regional Contest 1999
自己真正意义上刷的第一个DP题,这里写一下思路:
题意就是有6种物品,价值从1到6,每种物品的数目由输入决定,要求判断是否能分成两份,使每份价值相同。可以发现,这个题可以转换到多重背包问题,要注意的是,多重背包问题中有两个参数:体积和价值,这里只有一个价值参数,我们用数组保存价值就可以了,不需要建立结构体。
关于多重背包的问题,我会再写篇博客说明
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
int max(int a, int b) { return a > b ? a : b; }
int main(){
int pack[6], index = 1;;
while (cin >> pack[0] >> pack[1] >> pack[2] >> pack[3] >> pack[4] >> pack[5]){
if (pack[0] == 0 && pack[1] == 0 && pack[2] == 0 && pack[3] == 0 && pack[4] == 0 && pack[5] == 0)
break;
int sum = 0;
for (int i = 0; i < 6; ++i)
sum += pack[i]*(i+1);
if (sum % 2 != 0){ //如果价值总数是奇数,则直接认为不可分
printf("Collection #%d:\nCan't be divided.\n\n", index);
++index;
continue;
}
vector<int> pa;
for (int i = 0; i < 6; ++i){
int k = pack[i], c = 1;
while (k - c > 0){
k -= c;
pa.push_back(c*(i + 1));
c *= 2;
}
if(k != 0)
pa.push_back(k * (i+1));
}
vector<int> dp(sum+1);
dp[0] = 0;
for (unsigned i = 1; i < pa.size(); ++i){
for (int j = sum; j >= pa[i]; --j)
dp[j] = max(dp[j], dp[j-pa[i]] + pa[i]);
}
printf("Collection #%d:\n", index);
if (dp[sum / 2] == sum / 2)
printf("Can be divided.\n\n");
else printf("Can't be divided.\n\n");
++index;
}
return 0;
}