九度 題目1025:最大報銷額 (0/1揹包,動態規劃)

處理0/1揹包問題時,如果數據爲小數先將數據都乘10^n變成整數在處理~程序還可以優化,暫時沒想到好的辦法

  1. /**************************************************************  
  2.     Problem: 1025  
  3.     User: 1290605023  
  4.     Language: C  
  5.     Result: Accepted  
  6.     Time:30 ms  
  7.     Memory:4736 kb  
  8. ****************************************************************/ 
  9. #include<stdio.h>  
  10. #include<stdlib.h>  
  11. #include<string.h>  
  12.  
  13. int getMax(int *d,int n,int q)  
  14. {  
  15.     int i,j,re;  
  16.     int *f;  
  17.     f = (int *)malloc((q+1)*sizeof(int));  
  18.     for(i=0;i<=q;i++)  
  19.     {  
  20.         f[i] = 0;  
  21.     }  
  22.     for(i=1;i<=n;i++)  
  23.     {  
  24.         for(j=q;j>0;j--)  
  25.         {  
  26.             if(d[i-1]<=j)  
  27.             {  
  28.                 if(f[j-d[i-1]]+d[i-1] <= q && f[j] < f[j-d[i-1]]+d[i-1])  
  29.                     f[j] = f[j-d[i-1]]+d[i-1];  
  30.             }  
  31.         }  
  32.     }  
  33.     re = f[q];  
  34.     free(f);  
  35.     return re;  
  36. }  
  37.  
  38. int main(void)  
  39. {  
  40.     int N,m,i,j,max,*sum,price,Q,count=0,t=0;  
  41.     char type;  
  42.     char s[10000];  
  43.     double d_price,d_Q;  
  44.     while(scanf("%lf %d",&d_Q,&N) && N!=0)  
  45.     {  
  46.         Q = (int)(d_Q*100);  
  47.         sum = (int *)malloc(N*sizeof(int));  
  48.         for(i=0;i<N;i++)  
  49.         {  
  50.             scanf("%d",&m);  
  51.             for(j=0;j<m;j++)  
  52.             {  
  53.                 scanf(" %c:%lf",&type,&d_price);  
  54.                 price = (int)(d_price*100);  
  55.                 if(price<=60000 &&(type=='A'||type=='B'||type=='C'))  
  56.                     t += price;  
  57.                 else 
  58.                 {  
  59.                     if(j<m)  
  60.                         gets(s);  
  61.                     t=-1;  
  62.                     break;                
  63.                 }     
  64.             }  
  65.             if(t <= 100000 && t>0)  
  66.             {  
  67.                 sum[count++] = t;                 
  68.             }  
  69.             t=0;  
  70.         }  
  71.         max = getMax(sum,count,Q);  
  72.         printf("%.2lf\n",max/100.0);  
  73.         free(sum);  
  74.         max = 0;  
  75.         count=0;  
  76.     }  
  77.     return 0;  
  78. }  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章