Advertisement
Guest User

Untitled

a guest
Apr 9th, 2020
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.98 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. #define ff first
  4. #define ss second
  5.  
  6. int bfs(string s, string t)
  7. {
  8.     if(s == t)
  9.         return 0;
  10.     queue<pair<string, int> > q;
  11.     map<string, bool> mp;
  12.  
  13.     q.push({s, 0});
  14.     mp[s] = 1;
  15.  
  16.     string p, temp;
  17.     int x;
  18.     while(!q.empty())
  19.     {
  20.         p = q.front().ff;
  21.         x = q.front().ss;
  22.         q.pop();
  23.         for(int i = 0; i < p.size(); i++)
  24.         {
  25.             for(int j = i+1; j <= p.size(); j++)
  26.             {
  27.                 temp = p;
  28.                 reverse(temp.begin() + i, temp.begin() + j);
  29.                 if(mp[temp])
  30.                     continue;
  31.                 if(temp == t)
  32.                     return x+1;
  33.                 mp[temp] = 1;
  34.                 q.push({temp, x+1});
  35.             }
  36.         }
  37.     }
  38. }
  39.  
  40. int main()
  41. {
  42.     string s, t;
  43.     while(1)
  44.     {
  45.         cin >> s >> t;
  46.         if(s == "*" && t == "*")
  47.             break;
  48.         cout << bfs(s, t) << endl;
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement