Advertisement
SorahISA

[HLHSOJ d001] dfs + pruning

May 14th, 2020
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.20 KB | None | 0 0
  1. // #pragma GCC target("avx2")
  2. #pragma GCC optimize("O3", "unroll-loops")
  3.  
  4. // #include <bits/extc++.h>
  5. // using namespace __gnu_pbds;
  6.  
  7. #include <bits/stdc++.h>
  8. using namespace std;
  9.  
  10. #define int long long
  11. #define double long double
  12. // template <typename T>
  13. // using pbds_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
  14. using pii = pair<int, int>;
  15. template<typename T>
  16. using prior = priority_queue<T, vector<T>, greater<T>>;
  17. template<typename T>
  18. using Prior = priority_queue<T>;
  19.  
  20. #define X first
  21. #define Y second
  22. #define ALL(x) (x).begin(), (x).end()
  23. #define eb emplace_back
  24. #define pb push_back
  25.  
  26. #define fastIO() ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0)
  27. #define RANDOM() random_device __rd; \
  28.                  mt19937 __gen = mt19937(__rd()); \
  29.                  uniform_int_distribution<int> __dis(0, 1); \
  30.                  auto rnd = bind(__dis, __gen);
  31.  
  32. const int INF = 1E18;
  33. const int mod = 1E9 + 7;
  34.  
  35. int sz, sp, ep, limL, limR, minAns = 36;
  36. string s, t;
  37.  
  38. map<string, int> st;
  39.  
  40. void dfs(int lst, int dep) {
  41.     // if (dep <= 15) cout << dep << " : " << s << "\n";
  42.     if (s == t) {/*cout << "LOOK HERE !!! " << dep << "\n";*/ minAns = min(minAns, dep); return;}
  43.     if (dep >= minAns) return;
  44.     if (st[s] and st[s] <= dep) return;
  45.     st[s] = dep;
  46.    
  47.     for (int dx : {-2, -1, 1, 2}) {
  48.         if (dx == -lst) continue;
  49.         if (sp + dx < limL or sp + dx > limR) continue;
  50.         // if (sp + dx < 0 or sp + dx >= sz) continue;
  51.         swap(s[sp], s[sp + dx]), sp += dx;
  52.         pii rollback{limL, limR};
  53.         for (; s[limL] == t[limL] and s[limL] != '0'; ++limL);
  54.         for (; s[limR] == t[limR] and s[limR] != '0'; --limR);
  55.         dfs(dx, dep + 1);
  56.         limL = rollback.X, limR = rollback.Y;
  57.         swap(s[sp], s[sp - dx]), sp -= dx;
  58.     }
  59. }
  60.  
  61. int32_t main() {
  62.     fastIO();
  63.    
  64.     cin >> s >> t, sz = s.size();
  65.     for (sp = 0; s[sp] != '0'; ++sp);
  66.     for (ep = 0; t[ep] != '0'; ++ep);
  67.     for (limL =    0; s[limL] == t[limL] and s[limL] != '0'; ++limL);
  68.     for (limR = sz-1; s[limR] == t[limR] and s[limR] != '0'; --limR);
  69.    
  70.     dfs(0, 0);
  71.    
  72.     cout << minAns << "\n";
  73.    
  74.     return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement