Advertisement
Caio_25

Mochila01PD

May 1st, 2019
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.77 KB | None | 0 0
  1. #include<stdio.h>
  2.  
  3. typedef struct{
  4.  
  5.     float valor;
  6.     int peso;
  7. }item;
  8.  
  9. float mat[1000][1000];
  10. int contador = 0;
  11.  
  12. void iniciar_matriz();
  13. void imprimir(int n, int m);
  14. void cadastrar_itens(int n, item v[]);
  15. float maior(float a, float b);
  16. float mochila(int n, item v[], int peso_max);
  17.  
  18. int main()
  19. {
  20.     item v[1000];
  21.     int n;
  22.     int peso_max;
  23.  
  24.     iniciar_matriz();
  25.  
  26.     printf("Informe a qtd de itens: ");
  27.     scanf("%d", &n);
  28.  
  29.     cadastrar_itens(n, v);
  30.  
  31.     printf("Informe o peso maximo da mochila: ");
  32.     scanf("%d", &peso_max);
  33.  
  34.     printf("O maior valor que a mochila suporta vale: %f\n", mochila(n, v, peso_max));
  35.  
  36.     imprimir(n, peso_max);
  37.  
  38.     printf("Contador: %d\n", contador);
  39.  
  40. }
  41.  
  42. void iniciar_matriz()
  43. {
  44.     for(int i  = 0; i < 1000; i++)
  45.     {
  46.         for(int j = 0; j < 1000; j++)
  47.         {
  48.             mat[i][j] = 0;
  49.         }
  50.     }
  51. }
  52.  
  53. void imprimir(int n, int m)
  54. {
  55.     for(int i = 0; i <= n; i++)
  56.     {
  57.         for(int j = 0; j <= m; j++)
  58.         {
  59.             printf("%.2f\t", mat[i][j]);
  60.         }printf("\n");
  61.     }
  62. }
  63.  
  64. void cadastrar_itens(int n, item v[])
  65. {
  66.     for(int i = 1; i <= n;  i++)
  67.     {
  68.         printf("Informe o peso do item: ");
  69.         scanf("%d", &v[i].peso);
  70.  
  71.         printf("Informe o valor do item: ");
  72.         scanf("%f", &v[i].valor);
  73.     }
  74. }
  75.  
  76. float maior(float a, float b)
  77. {
  78.     if(a > b)
  79.     {
  80.         return(a);
  81.     }
  82.  
  83.     else
  84.     {
  85.         return(b);
  86.     }
  87. }
  88.  
  89. float mochila(int n, item v[], int peso_max)
  90. {
  91.     contador = contador + 1;
  92.     if(n <= 0)
  93.     {
  94.         return(0);
  95.     }
  96.  
  97.     else
  98.     {
  99.  
  100.         mat[n-1][peso_max] = mochila(n-1, v, peso_max);
  101.  
  102.         if(v[n].peso <= peso_max)
  103.         {
  104.  
  105.             mat[n-1][peso_max - v[n].peso] = v[n].valor + mochila(n - 1, v, peso_max - v[n].peso);
  106.  
  107.             mat[n][peso_max] = maior(mat[n-1][peso_max - v[n].peso], mat[n-1][peso_max]);
  108.  
  109.             return(  mat[n][peso_max] );
  110.         }
  111.  
  112.         else
  113.         {
  114.             return(mat[n-1][peso_max]);
  115.         }
  116.     }
  117. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement