Advertisement
seulunga

Untitled

Feb 24th, 2019
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.81 KB | None | 0 0
  1. #include <iostream>
  2. #include <unordered_set>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. struct DPState {
  8.   int pos;
  9.   int last_jump;
  10.  
  11.   std::size_t operator()(DPState const& s) const noexcept {
  12.     std::size_t h1 = std::hash<int>{}(s.pos);
  13.     std::size_t h2 = std::hash<int>{}(s.last_jump);
  14.     return h1 ^ (h2 << 1);
  15.   }
  16.  
  17.   bool operator()(const DPState& lhs, const DPState& rhs) const {
  18.     return lhs.pos == rhs.pos && lhs.last_jump == rhs.last_jump;
  19.   }
  20. };
  21.  
  22. using DPStateSet = unordered_set<DPState, DPState, DPState>;
  23.  
  24. bool can_cross(const unordered_set<int>& stones, int pos, int last_jump,
  25.                int target, DPStateSet* already_explored) {
  26.   if (pos == target) {
  27.     return true;
  28.   }
  29.   DPState dp_state({/*pos=*/pos, /*last_jump=*/last_jump});
  30.   if (already_explored->count(dp_state)) {
  31.     return false;
  32.   }
  33.  
  34.   unordered_set<int> possible_jumps = {last_jump, last_jump + 1};
  35.   if (last_jump > 1) {
  36.     possible_jumps.insert(last_jump - 1);
  37.   }
  38.   for (int jump : possible_jumps) {
  39.     int new_pos = pos + jump;
  40.     if (stones.count(new_pos) > 0) {
  41.       if (can_cross(stones, new_pos, jump, target, already_explored)) {
  42.         return true;
  43.       }
  44.     }
  45.   }
  46.   already_explored->insert(dp_state);
  47.   return false;
  48. }
  49.  
  50. class Solution {
  51. public:
  52.   bool canCross(const vector<int>& stones_vec) {
  53.     unordered_set<int> stones(stones_vec.begin(), stones_vec.end());
  54.     if (stones.count(1) == 0) {
  55.       return false;
  56.     }
  57.     DPStateSet already_explored;
  58.     return can_cross(stones, /*pos=*/1, /*last_jump=*/1, stones_vec.back(),
  59.                      &already_explored);
  60.   }
  61. };
  62.  
  63. int main() {
  64.   // [0,1,3,5,6,8,12,17]
  65.   // [0,1,3,4,5,7,9,10,12]
  66.   // [0,1,2,3,4,8,9,11]
  67.   // [0,1]
  68.   // [0,2]
  69.   cout << Solution().canCross({0, 1, 3, 5, 6, 8, 12, 17}) << endl;
  70.   return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement