處理0/1揹包問題時,如果數據爲小數先將數據都乘10^n變成整數在處理~程序還可以優化,暫時沒想到好的辦法
- /**************************************************************
- Problem: 1025
- User: 1290605023
- Language: C
- Result: Accepted
- Time:30 ms
- Memory:4736 kb
- ****************************************************************/
- #include<stdio.h>
- #include<stdlib.h>
- #include<string.h>
- int getMax(int *d,int n,int q)
- {
- int i,j,re;
- int *f;
- f = (int *)malloc((q+1)*sizeof(int));
- for(i=0;i<=q;i++)
- {
- f[i] = 0;
- }
- for(i=1;i<=n;i++)
- {
- for(j=q;j>0;j--)
- {
- if(d[i-1]<=j)
- {
- if(f[j-d[i-1]]+d[i-1] <= q && f[j] < f[j-d[i-1]]+d[i-1])
- f[j] = f[j-d[i-1]]+d[i-1];
- }
- }
- }
- re = f[q];
- free(f);
- return re;
- }
- int main(void)
- {
- int N,m,i,j,max,*sum,price,Q,count=0,t=0;
- char type;
- char s[10000];
- double d_price,d_Q;
- while(scanf("%lf %d",&d_Q,&N) && N!=0)
- {
- Q = (int)(d_Q*100);
- sum = (int *)malloc(N*sizeof(int));
- for(i=0;i<N;i++)
- {
- scanf("%d",&m);
- for(j=0;j<m;j++)
- {
- scanf(" %c:%lf",&type,&d_price);
- price = (int)(d_price*100);
- if(price<=60000 &&(type=='A'||type=='B'||type=='C'))
- t += price;
- else
- {
- if(j<m)
- gets(s);
- t=-1;
- break;
- }
- }
- if(t <= 100000 && t>0)
- {
- sum[count++] = t;
- }
- t=0;
- }
- max = getMax(sum,count,Q);
- printf("%.2lf\n",max/100.0);
- free(sum);
- max = 0;
- count=0;
- }
- return 0;
- }