Advertisement
icatalin

problema rucsacului greedy

May 30th, 2018
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.36 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct
  5. {
  6.     int id;
  7.     double greutate, castig;
  8. }Obiect;
  9.  
  10. int cmpObiecte(const void *a, const void *b) // ord descr
  11. {
  12.     Obiect va = *(Obiect *)a;
  13.     Obiect vb = *(Obiect *)b;
  14.    
  15.     if (va.castig /va.greutate < vb.castig / vb.greutate)
  16.         return 1;
  17.    
  18.     if (va.castig /va.greutate > vb.castig / vb.greutate)
  19.         return 0;
  20. }
  21.  
  22.  
  23. int main()
  24. {
  25.     int n,i;
  26.     double G, ct, auxG, p;
  27.    
  28.     Obiect *ob;
  29.     FILE *fin, *fout;
  30.     fin = fopen("rucsac.in","r");
  31.    
  32.     fscanf(fin,"%d",&G);
  33.     fscanf(fin,"%d",&n);
  34.    
  35.     ob = (Obiect*) malloc(n*sizeof(Obiect));
  36.    
  37.     for (i=0; i<n; i++)
  38.     {
  39.         ob[i].id = i+1;
  40.         fscanf(fin,"%d %d",&ob[i].castig,&ob[i].greutate)
  41.     }
  42.    
  43.     fclose(fin);
  44.    
  45.     qsort(ob,n,sizeof(Obiect),cmpObiecte);
  46.     auxG = G;
  47.     ct = 0;
  48.     for (i=0; i<n; i++)
  49.         if(ob[i].greutate <= auxG)
  50.     {
  51.         printf("obiectul %d: 100%%\n",ob[i].id);
  52.         ct = ct + ob[i].castig;
  53.         auxG = auxG - ob[i].greutate;
  54.     }
  55.     else
  56.     {
  57.         p = auxG/ob[i].greutate;
  58.         printf("obiectul %d: %.2f%%\n",ob[i].id,p*100);
  59.         ct = ct + p * ob[i].castig;
  60.         auxG = 0;
  61.         break;
  62.     }
  63.    
  64.     printf("Castigul total este: %d\n",ct);
  65.     fclose(fout);
  66.    
  67.     free(ob);
  68.    
  69.     return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement