完全背包的二进制优化
时间:2014-03-26 13:52:59
收藏:0
阅读:589
完全背包可以通过二进制优化降低时间复杂度:
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.
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.
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.
代码:
1 #include <iostream> 2 #include <string.h> 3 #include <stdio.h> 4 using namespace std; 5 6 const int maxn=20005; 7 int va[maxn]; 8 int dp[maxn*6]; 9 int a[7]; 10 11 int main() 12 { 13 int kase=1; 14 //freopen("aa.txt","r",stdin); 15 while(scanf("%d %d %d %d %d %d",&a[1],&a[2],&a[3],&a[4],&a[5],&a[6])) 16 { 17 int sum=0; 18 for(int i=1;i<=6;i++) 19 sum+=i*a[i]; 20 21 if(sum==0) 22 break; 23 24 printf("Collection #%d:\n",kase++); 25 if(sum%2==1) 26 { 27 printf("Can‘t be divided.\n\n"); 28 continue; 29 } 30 31 int all=sum/2; 32 int cnt=0; 33 for(int i=1;i<=6;i++) 34 { 35 if(a[i]) 36 { 37 for(int k=1;k<=a[i];k*=2) 38 { 39 va[cnt++]=k*i; 40 a[i]-=k; 41 } 42 if(a[i]>0) 43 { 44 va[cnt++]=a[i]*i; 45 } 46 } 47 } 48 memset(dp,0,sizeof(dp)); 49 for(int i=0;i<cnt;i++) 50 { 51 for(int j=all;j>=va[i];j--) 52 { 53 if(j-va[i]>=0) 54 dp[j]=max(dp[j],dp[j-va[i]]+va[i]); 55 } 56 } 57 if(all==dp[all]) 58 printf("Can be divided.\n\n"); 59 else 60 printf("Can‘t be divided.\n\n"); 61 } 62 return 0; 63 }
原文:http://www.cnblogs.com/zhanzhao/p/3625186.html
评论(0)