[POJ 1014] 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.
輸入格式
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.
輸出格式
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.
樣例輸入輸出
樣例輸入
1 0 1 2 0 0
1 0 0 0 1 1
0 0 0 0 0 0
樣例輸出
Collection #1:
Can‘t be divided.
Collection #2:
Can be divided.
題意概括
給定六種硬幣,第i種硬幣的價值為i,輸入每種硬幣的數量ni,判斷這些硬幣能否分成價值相同的兩組。
解析
首先,如果硬幣的價值\(sum\)總數不是2的倍數,那麽無論如何都無法分成價值相同的兩組,直接輸入即可。否則,每組的價值總數就是\(sum/2\)。那麽問題就轉化為已知硬幣的數量和價值,從中選出一些硬幣,問能否使這些硬幣的價值綜合為\(sum/2\)(如果一組為\(sum/2\),那麽另一組也肯定為\(sum/2\))。這顯然就可以用多重背包的方法來實現了。將這個背包的容積設為\(sum/2\),每個硬幣的價值和體積都為自己的價值,最後只需要判斷總體積為\(sum/2\)時總價值是否也為\(sum/2\)即可。
另外,因為數量特別龐大,這裏的多重背包需要使用二進制優化。
代碼
#include <iostream>
#include <cstdio>
#include <cstring>
#define N 1000000
#define M 1000000
using namespace std;
int n,w,i,j,c[N],v[N],num[N],nc[N],nv[N],ncnt,sum,f[M],cnt;
int main()
{
for(i=1;i<=6;i++) c[i]=i;
while(1){
cnt++;
sum=ncnt=0;
memset(f,0,sizeof(f));
for(i=1;i<=6;i++){
cin>>num[i];
sum+=num[i]*i;
}
if(sum==0) break;
cout<<"Collection #"<<cnt<<":"<<endl;
if(sum%2==1){
cout<<"Can't be divided."<<endl<<endl;
continue;
}
else w=sum/2;
for(i=1;i<=6;i++){
int k;
for(k=1;num[i]-(1<<k)+1>0;k++){
ncnt++;
nc[ncnt]=(1<<(k-1))*c[i];
}
ncnt++;
k--;
nc[ncnt]=(num[i]-(1<<k)+1)*c[i];
}
for(i=1;i<=ncnt;i++){
for(j=w;j>=nc[i];j--){
f[j]=max(f[j],f[j-nc[i]]+nc[i]);
}
}
if(f[w]!=w) cout<<"Can't be divided."<<endl;
else cout<<"Can be divided."<<endl;
cout<<endl;
}
return 0;
}
[POJ 1014] Dividing