hdu 1059 Dividing(pku 1042)
http://acm.hdu.edu.cn/showproblem.php?pid=1059
http://poj.org/problem?id=1014
多重背包
这个题有两种AC的方法一种是采用多重背包的方法,但是这个方法会超时,所以就加了一个取模(这是错误的地方)来减少时间,这个方法可以AC,但却是错误的 12 0 0 0 0 1 这组数据就不能正确的出结果;
View Code
1 #include<cstdio>
2 #include<iostream>
3 #include<algorithm>
4 #include<cstring>
5 using namespace std;
6 int main()
7 {
8 int s[7],w,count=0,ans[10010],sum,i,j,k;
9 while(scanf("%d%d%d%d%d%d",&s[1],&s[2],&s[3],&s[4],&s[5],&s[6]),s[1]||s[2]||s[3]||s[4]||s[5]||s[6])
10 {
11 s[1]%=60;
12 s[2]%=60;
13 s[3]%=60;
14 s[4]%=60;
15 s[5]%=60;
16 s[6]%=60;
17 count++;
18 printf("Collection #%d:\n",count);
19 w=s[1]+2*s[2]+3*s[3]+4*s[4]+5*s[5]+6*s[6];
20 if(w%2)
21 {
22 printf("Can't be divided.\n\n");
23 continue;
24 }
25 sum=w/2;
26 memset(ans,0,sizeof(ans));
27 ans[0]=1;
28 for(i=1;i<=6;i++)
29 {
30 for(j=1;j<=s[i];j++)
31 for(k=sum;k>=i;k--)
32 if(ans[k-i])
33 ans[k]=1;
34 }
35 if(ans[sum])
36 printf("Can be divided.\n\n");
37 else
38 printf("Can't be divided.\n\n");
39 }
40 }
正确的方法是采用二分的多重背包;
View Code
1 #include<iostream>
2 using namespace std;
3 int m1[60001],m2[120010];
4 int array[7];
5 void calc(int *s,int m,int n)
6 {
7 int i,j,k,sum=0,rest;
8 for(i=1;i<60001;i++) s[i]=0;
9 s[0]=1;
10 for(i=m;i<=n;i++)
11 {
12 sum+=array[i]*i;
13 for(j=1;j<array[i];j*=2)
14 {
15 for(k=sum;k>=j*i;k--)
16 if(s[k]==0&&s[k-j*i])
17 s[k]=1;
18 }
19 j=array[i]-j/2;
20 for(k=sum;k>=j*i;k--)
21 if(s[k]==0&&s[k-j*i])
22 s[k]=1;
23 }
24 }
25 int main()
26 {
27 int i,times=1,a,flag;
28 while(cin>>array[1])
29 {
30 flag=0;
31 array[0]=0;
32 for(i=2;i<7;i++)
33 {
34 cin>>array[i];
35 array[0]+=array[i]*i;
36 }
37 array[0]+=array[1];
38 if(array[0]==0) break;
39 if(array[0]%2) {cout<<"Collection #"<<times++<<":"<<endl;cout<<"Can't be divided.\n"<<endl;continue;}
40 array[0]/=2;
41 calc(m1,1,3);
42 calc(m2,4,6);
43 for(i=0;i<=array[0];i++)
44 if(m1[i]&&m2[array[0]-i])
45 {
46 flag=1;break;
47 }
48 cout<<"Collection #"<<times++<<":"<<endl;
49 if(flag) cout<<"Can be divided."<<endl;
50 else cout<<"Can't be divided."<<endl;
51 cout<<endl;
52 }
53 return 0;
54 }