Advertisement
informaticage

Greedy Santa

Dec 23rd, 2019
326
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1. /**
  2.     Training OIS
  3.     Greedy Santa ( christmas )
  4.     https://training.olinfo.it/#/task/ois_christmas
  5.  
  6.     Author: Samuel Finocchio
  7.     Date: 23/12/2019
  8.     Solution 1: [ 19:36, 19:50 ] ( 50/100 ) Timeout
  9.     Solution 2: [ 21:17, 21:22 ] ( 100/100 ) Added memoization
  10. **/
  11.  
  12. #include <iostream>
  13. #include <vector>
  14. #include <limits>
  15. #include <unordered_map>
  16.  
  17. using namespace std;
  18.  
  19. int solve ( vector < int > gifts, int index, int expense, int budget, unordered_map<string, int> &MEMO );
  20.  
  21. int main ( void )
  22. {
  23.     int giftsAmount, budget;
  24.     cin >> giftsAmount >> budget;
  25.  
  26.     vector <int> gifts ( giftsAmount );
  27.  
  28.     int maximumExpense = 0;
  29.     for ( int i = 0; i < giftsAmount; i++ ) {
  30.         cin >> gifts [ i ];
  31.         maximumExpense = maximumExpense + gifts [ i ];
  32.     }
  33.  
  34.     if ( maximumExpense <= budget )
  35.         cout << maximumExpense;
  36.     else {
  37.         unordered_map <string, int> MEMO;
  38.         cout << solve ( gifts, 0, 0, budget, MEMO );
  39.     }
  40.  
  41.     return 0;
  42. }
  43.  
  44. int solve ( vector < int > gifts, int index, int expense, int budget, unordered_map <string, int> &MEMO ) {
  45.     string memoIndex = to_string ( index ) + " - " + to_string ( expense );
  46.  
  47.     if ( MEMO.find ( memoIndex ) != MEMO.end() )
  48.         return MEMO [ memoIndex ];
  49.  
  50.     if ( expense >= budget ) {
  51.         MEMO [ memoIndex ] = expense;
  52.         return expense;
  53.     }
  54.  
  55.     if ( index == gifts.size() ) {
  56.         MEMO [ memoIndex ] = numeric_limits<int>::max();
  57.         return numeric_limits<int>::max();
  58.     }
  59.  
  60.     int result = min (
  61.         solve ( gifts, index + 1, expense + gifts [ index ], budget, MEMO ),
  62.         solve ( gifts, index + 1, expense, budget, MEMO )
  63.     );
  64.  
  65.     MEMO [ memoIndex ] = result;
  66.     return result;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement