首页 > 代码库 > Poj 1014

Poj 1014

传送门:http://poj.org/problem?id=1014

 

第一次碰到多重背包

刚开始还想一言不合就dfs但是会超时啊……看了别人的才知道是多重背包

http://blog.csdn.net/zxy_snow/article/details/6169008

http://blog.csdn.net/zcube/article/details/48223063

主要是看了这两个

 1 #include<iostream>
 2 #include<cstring>
 3 using namespace std;
 4 
 5 int con,sum;
 6 int marble[300010];
 7 int bag[300010];
 8 int a,b,c,d,e,f;
 9 int num;
10 int k;
11 
12 void split(int x,int n){
13     int temp=0;
14     int m;
15     for(int i=0; ;i++){
16         m=1<<i;
17         if(m+temp>x){
18             break;
19         }
20         marble[num++]=m*n;
21         temp+=m;
22     }
23     if(x-temp>0){
24         marble[num++]=(x-temp)*n;
25     }
26 }
27 
28 bool dp(){
29     for(int i=0;i<num;i++){
30         for(int j=sum;j>=marble[i];j--){
31             if((bag[j-marble[i]]+marble[i])>bag[j]){
32                 bag[j]=bag[j-marble[i]]+marble[i];
33             }
34         }
35     }
36     return bag[sum]==sum;
37 }
38 
39 int main(){
40     k=0;
41     while(cin>>a>>b>>c>>d>>e>>f){
42         if(!(a||b||c||d||e||f)){
43             break;
44         }
45         k++;
46         cout<<"Collection #"<<k<<":"<<endl;
47         sum=0;
48         num=0;
49         sum+=a;
50         sum+=b*2;
51         sum+=c*3;
52         sum+=d*4;
53         sum+=e*5;
54         sum+=f*6;
55         if(sum%2==1){
56             cout<<"Can‘t be divided."<<endl<<endl;
57             continue;
58         }
59         sum=sum/2;
60         memset(marble,0,sizeof(marble));
61         split(a,1);
62         split(b,2);
63         split(c,3);
64         split(d,4);
65         split(e,5);
66         split(f,6);
67         memset(bag,0,sizeof(bag));
68         if(dp()){
69             cout<<"Can be divided."<<endl<<endl;
70         }
71         else{
72             cout<<"Can‘t be divided."<<endl<<endl;
73         }
74     }
75 } 

 

Poj 1014