Advertisement
guilhermedelima

I.cpp

Dec 22nd, 2014
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.82 KB | None | 0 0
  1. #include <iostream>
  2. #include <string.h>
  3.  
  4. using namespace std;
  5.  
  6. #define MAX_WEIGHT 50
  7. #define MAX_PACKAGE 100
  8.  
  9. struct package{
  10.     long toy;
  11.     long weight;
  12. };
  13.  
  14. int main(void){
  15.  
  16.     ios::sync_with_stdio(false);
  17.  
  18.     long T, N, final_weight;
  19.     long matrix[MAX_PACKAGE+1][MAX_WEIGHT+1];
  20.     long count_package[MAX_PACKAGE+1][MAX_WEIGHT+1];
  21.     package list[MAX_PACKAGE];
  22.  
  23.     cin >> T;
  24.  
  25.     for(int k=0; k<T; k++){
  26.  
  27.         cin >> N;
  28.  
  29.         memset(matrix, 0, sizeof(matrix));
  30.         memset(count_package, 0, sizeof(count_package));
  31.  
  32.         for(long i=0; i<N; i++){
  33.             cin >> list[i].toy >> list[i].weight;
  34.         }
  35.  
  36.         for(long i=1; i<=N; i++){
  37.             for(long j=1; j<=MAX_WEIGHT; j++){
  38.  
  39.                 if( list[i-1].weight <= j && matrix[i-1][j-list[i-1].weight] + list[i-1].toy >= matrix[i-1][j] ){
  40.  
  41.                     matrix[i][j] = matrix[i-1][j-list[i-1].weight] + list[i-1].toy;
  42.  
  43.                     if( matrix[i-1][j-list[i-1].weight] + list[i-1].toy == matrix[i-1][j] )
  44.                         count_package[i][j] = min(count_package[i-1][j], count_package[i-1][j-list[i-1].weight] + 1);
  45.                     else
  46.                         count_package[i][j] = count_package[i-1][j-list[i-1].weight] + 1;
  47.                
  48.                 }else{
  49.                     matrix[i][j] = matrix[i-1][j];
  50.                     count_package[i][j] = count_package[i-1][j];
  51.                 }
  52.             }
  53.         }
  54.  
  55.         for(final_weight=MAX_WEIGHT; final_weight&&matrix[N][final_weight]==matrix[N][final_weight-1]; final_weight--);
  56.  
  57.         cout << matrix[N][final_weight] << " brinquedos" << endl;
  58.         cout << "Peso: " << final_weight << " kg" << endl;
  59.         cout << "sobra(m) " << N - count_package[N][final_weight] << " pacote(s)" << endl << endl;
  60.     }
  61.  
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement