Mary and Rose own a collection of jewells. They want to split the collection among themselves so that both receive an equal share of the jewels. This would be easy if all the jewels had the same value, because then they could just split the collection in half. But unfortunately, some of the jewels are larger, or more beautiful than others. So, Mary and Rose start by assigning a value, a natural number between one and ten, to each jewel. Now they want to divide the jewels so that each of them gets the same total value. Unfortunately, they realize that it might be impossible to divide the jewels in this way (even if the total value of all jewels is even). For example, if there are one jewel 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 jewels.
输入描述:
Each line in the input file describes one collection of jewels to be divided. The lines contain ten non-negative integers n1 , . . . , n10 , where ni is the number of jewels of value i. The maximum total number of jewells will be 10000.
The last line of the input file will be "0 0 0 0 0 0 0 0 0 0"; do not process this line.
</span>
输出描述:
For each collection, output "#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.
思路:我们令背包容量为sum(所有物品的总价值和)/2,然后令第i堆物品的价值和重量都为i,可知背包价值上限就是sum/2,如果最后能取得的最大价值为sum/2,那么说明可以划分,否则说明不能划分。
#include<set>
#include<map>
#include<cmath>
#include<string>
#include<cstring>
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn = 100005;
int dp[maxn];
int c[12];
int v; // 背包容量
// 01背包
void ZeroOnepark(int val, int vol)
{
for (int j = v ; j >= vol; j--)
{
dp[j] = max(dp[j], dp[j - vol] + val);
}
}
// 完全背包
void Completepark(int val, int vol)
{
for (int j = vol; j <= v; j++)
{
dp[j] = max(dp[j], dp[j - vol] + val);
}
}
// 多重背包
void Multiplepark(int val, int vol, int amount)
{
if (vol * amount >= v)
{
Completepark(val, vol);
}
else
{
int k = 1;
while (k < amount)
{
ZeroOnepark(k * val, k * vol);
amount -= k;
k <<= 1;
}
if (amount > 0)
{
ZeroOnepark(amount * val, amount * vol);
}
}
}
int main()
{
int t = 1;
while (true)
{
bool flag = false;
int sum = 0, num = 0;
for(int i = 1 ; i <= 10 ; i++)
{
cin >> c[i];
num += c[i];
sum += i * c[i];
if(c[i] > 0)
flag = true;
//cin >> volume[i] >> value[i] >> c[i]; // 费用,价值,数量
}
if(!flag)break;
if(t > 1)
cout << endl;
if(sum & 1)
{
printf("#%d:Can't be divided.\n", t++);
continue;
}
v = sum / 2;
memset(dp, 0, sizeof(dp));
for (int i = 1; i <= 10; i++)
{
Multiplepark(i, i, c[i]);
}
if(dp[v] == v)
printf("#%d:Can be divided.\n", t++);
else
printf("#%d:Can't be divided.\n", t++);
}
return 0;
}