Advertisement
seulunga

Untitled

Feb 18th, 2019
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.97 KB | None | 0 0
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <limits>
  4. #include <string>
  5. #include <unordered_map>
  6. #include <unordered_set>
  7. #include <vector>
  8.  
  9. using namespace std;
  10.  
  11. string get_key(int color, int index) {
  12.   string res;
  13.   res.append(to_string(color));
  14.   res.append("-");
  15.   res.append(to_string(index));
  16.   return res;
  17. }
  18.  
  19. int cost_from_here(const vector<vector<int>>& costs, int index_house,
  20.                    int prev_color, unordered_map<string, int>* cost_map) {
  21.   if (index_house == costs.size()) {
  22.     return 0;
  23.   }
  24.   string key = get_key(prev_color, index_house);
  25.   auto it = cost_map->find(key);
  26.   if (it != cost_map->end()) {
  27.     return it->second;
  28.   }
  29.   int cost = numeric_limits<int>::max();
  30.   for (int c : {0, 1, 2}) {
  31.     if (c != prev_color) {
  32.       cost = min(cost, costs[index_house][c] +
  33.                            cost_from_here(costs, index_house + 1, c, cost_map));
  34.     }
  35.   }
  36.   (*cost_map)[key] = cost;
  37.   return cost;
  38. }
  39.  
  40. vector<int> get_other_colors(int c) {
  41.   unordered_set<int> s = {0, 1, 2};
  42.   s.erase(c);
  43.   return vector<int>(s.begin(), s.end());
  44. }
  45.  
  46. int cost_from_here_dp(const vector<vector<int>>& costs) {
  47.   if (costs.empty()) {
  48.     return 0;
  49.   }
  50.   vector<int> prev(3, 0);
  51.   for (int i = costs.size() - 1; i >= 0; i--) {
  52.     vector<int> cur(3, numeric_limits<int>::max());
  53.     for (int c : {0, 1, 2}) {
  54.       vector<int> other_colors = get_other_colors(c);
  55.       for (int oc : other_colors) {
  56.         cur[c] = min(cur[c], prev[oc] + costs[i][c]);
  57.       }
  58.     }
  59.     swap(prev, cur);
  60.   }
  61.   return min(prev[0], min(prev[1], prev[2]));
  62. }
  63.  
  64. class Solution {
  65. public:
  66.   int minCost(const vector<vector<int>>& costs) {
  67.     return cost_from_here_dp(costs);
  68.     // unordered_map<string, int> cost_map;
  69.     // return cost_from_here(costs, /*index_house=*/0, /*prev_color=*/-1,
  70.     //                       &cost_map);
  71.   }
  72. };
  73.  
  74. int main() {
  75.   Solution().minCost({{17, 2, 13}, {16, 16, 5}, {14, 3, 19}, {40, 20, 4}});
  76.   return 0;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement