hdu2844---多重背包

http://acm.hdu.edu.cn/showproblem.php?pid=2844

Coins

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 825    Accepted Submission(s): 336


Problem Description
Whuacmers use coins.They have coins of value A1,A2,A3...An Silverland dollar. One day Hibix opened purse and found there were some coins. He decided to buy a very nice watch in a nearby shop. He wanted to pay the exact price(without change) and he known the price would not more than m.But he didn't know the exact price of the watch.

You are to write a program which reads n,m,A1,A2,A3...An and C1,C2,C3...Cn corresponding to the number of Tony's coins of value A1,A2,A3...An then calculate how many prices(form 1 to m) Tony can pay use these coins.
 

 

Input
The input contains several test cases. The first line of each test case contains two integers n(1 ≤ n ≤ 100),m(m ≤ 100000).The second line contains 2n integers, denoting A1,A2,A3...An,C1,C2,C3...Cn (1 ≤ Ai ≤ 100000,1 ≤ Ci ≤ 1000). The last test case is followed by two zeros.
 

 

Output
  
For each test case output the answer on a single line.
 
Sample Input
3 101 2 4 2 1 12 51 4 2 10 0
Sample Output
84
 

我写了个程序,在hdu上因为时间太长而过不去,希望有人能给我提出优化

方案,不胜感激。

代码
1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<string.h>
4  int a[101],c[101],sum,f[2][200001],n,m;
5
6  int main(){
7 int i,j,k;
8 scanf("%d%d",&n,&m);
9 while((m+n)!=0)
10 {
11 sum=0;
12 memset(f,0,sizeof(f));
13
14 for(i=1;i<=n;i++)
15 scanf("%d",&a[i]);
16 for(i=1;i<=n;i++)
17 scanf("%d",&c[i]);
18
19 f[0][0]=1;
20 for(i=1;i<=n;i++)
21 for(j=1;j<=m;j++)
22 for(k=0;k<=c[i];k++)
23 {
24 if(f[i%2][j]==1)break;
25 if(j-k*a[i]>0)
26 { if(f[(i-1)%2][j-k*a[i]])f[i%2][j]=1;}
27 if(j-k*a[i]==0)f[i%2][j]=1;
28 }
29 for(i=1;i<=m;i++)
30 if(f[n%2][i]==1)sum++;
31 printf("%d\n",sum);
32
33 scanf("%d%d",&n,&m);
34 }
35 return 0;
36 }
37  

 

其实已经有了优化了的程序,只是看不懂,希望有人可以指点一下程序思想,以下为优化后的程序:

代码
1 #include<cstdio>
2 #include<stdlib.h>
3  int a[120],c[120];
4 bool f[100050];
5 int main()
6 {
7 int n,m,i,j,k,t,left,count;
8 while(scanf("%d%d",&n,&m),n||m)
9 {
10 for(i=0;i<n;i++)
11 scanf("%d",&a[i]);
12 for(i=0;i<n;i++)
13 scanf("%d",&c[i]);
14
15 for(i=1;i<=m;i++)
16 f[i]=false;
17
18 f[0]=true;
19
20 for(i=0;i<n;i++)
21 {
22 left=c[i];
23 for(k=1;k<=left;k<<=1)
24 {
25 t=k*a[i];
26 for(j=m;j>=t;j--)
27 if(f[j-t])
28 f[j]=true;
29 left-=k;
30 }
31
32 if(left)
33 {
34 t=left*a[i];
35 for(j=m;j>=t;j--)
36 if(f[j-t])
37 f[j]=true;
38 }
39 }
40
41 count=0;
42 for(i=1;i<=m;i++)
43 if(f[i])
44 count++;
45
46 printf("%d\n",count);
47 }
48 return 0;
49 }
50
51

 其实就是二进制啊。比如对13这个数,用1 2 4 6这几个数就可以完全表示13以内的所有正数,这就是优化的原理。

 

posted @ 2010-07-23 17:16  Danty  阅读(516)  评论(0编辑  收藏  举报