ZOJ - 1149 Dividing
ZOJ - 1149 (Crawling
failed)
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.
The last line of the input file will be ``0 0 0 0 0 0''; do not process this line.
Output a blank line after each test case.
1 0 1 2 0 0
Collection #1: Collection #2: Source
Mid-Central European Regional Contest 1999
|
思路:多层背包,直接搞会T,二进制拆分优化:就是1,2,4,2^k(满足和小于分解数最大的k),二进制优化可行的原因,因为可以用二进制数表示任意不同小于等于k的数。
#pragma comment(linker, "/STACK:1024000000,1024000000") #include <iostream> #include <algorithm> #include <cstdio> #include <cstring> #include <string> #include <queue> #include <map> #include <stack> #include <set> #include <cmath> #include <vector> #define INF 0x3f #define eps 1e-6 #define moo 1000000007 const int N=1100000; using namespace std; int n,m; struct Rice { int weight; int number; }rice[N]; int dp[N]; //完全背包 void CompletePack(int weight) { for(int i=weight;i<=n;i++) { dp[i]=max(dp[i],dp[i-weight]+weight); } } //01背包 void ZeroOnePack(int weight) { for(int i=n;i-weight>=0;i--) { dp[i]=max(dp[i],dp[i-weight]+weight); } } //多重背包 void MultiplePack(int weight,int number) { //如果大于等于金额,就按完全背包处理(此时相当于不限定袋数) if(weight*number>=n) { CompletePack(weight); return ; } int k=1; while(k<number) { ZeroOnePack(k*weight); number-=k; k*=2; } ZeroOnePack(number*weight); } int main() { int T=1; while(1) { int flag=0; n=0; for(int i=1;i<=6;i++) rice[i].weight=i; memset(dp,0,sizeof(dp)); for(int i=1;i<=6;i++) { scanf("%d",&rice[i].number); n+=rice[i].number*rice[i].weight; flag|=rice[i].number; } if(!flag) break; for(int i=1;i<=6;i++) { MultiplePack(rice[i].weight,rice[i].number); } printf("Collection #%d:\n",T++); if(dp[n/2]==n/2 && n%2==0) { printf("Can be divided.\n\n"); } else { printf("Can't be divided.\n\n"); } // printf("%d\n",dp[n/2]); } return 0; }