fork(7) download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int main() {
  4. int t;
  5. cin>>t;
  6. while(t--){
  7. unordered_map<string,int> vis;
  8. string s,f;
  9. int n;
  10. cin>>s>>f;
  11. n=s.length();
  12. int pos = 0;
  13. for(int i = 0 ; i<s.length(); i++){
  14. if(s[i]=='_'){
  15. pos = i;
  16. break;
  17. }
  18. }
  19. queue<pair<string,int> > q;
  20. q.push({s,pos});
  21. vis[s]=0;
  22. while(!q.empty()){
  23. string ss = q.front().first;
  24. int pp = q.front().second;
  25. int dist = vis[ss];
  26. q.pop();
  27. if(pp>0){
  28. swap(ss[pp],ss[pp-1]);
  29. if(!vis.count(ss)){
  30. if(ss==f){
  31. cout<<dist+1<<"\n";
  32. break;
  33. }
  34. vis[ss]=dist+1;
  35. q.push({ss,pp-1});
  36. }
  37. swap(ss[pp],ss[pp-1]);
  38. }
  39. if(pp<n-1){
  40. swap(ss[pp],ss[pp+1]);
  41. if(!vis.count(ss)){
  42. if(ss==f){
  43. cout<<dist+1<<"\n";
  44. break;
  45. }
  46. vis[ss]=dist+1;
  47. q.push({ss,pp+1});
  48. }
  49. swap(ss[pp],ss[pp+1]);
  50. }
  51. if(pp>1 && ss[pp-1]!=ss[pp-2]){
  52. swap(ss[pp],ss[pp-2]);
  53. if(!vis.count(ss)){
  54. if(ss==f){
  55. cout<<dist+1<<"\n";
  56. break;
  57. }
  58. vis[ss]=dist+1;
  59. q.push({ss,pp-2});
  60. }
  61. swap(ss[pp],ss[pp-2]);
  62. }
  63. if(pp<n-2 && ss[pp+1]!=ss[pp+2]){
  64. swap(ss[pp],ss[pp+2]);
  65. if(!vis.count(ss)){
  66. if(ss==f){
  67. cout<<dist+1<<"\n";
  68. break;
  69. }
  70. vis[ss]=dist+1;
  71. q.push({ss,pp+2});
  72. }
  73. swap(ss[pp],ss[pp+2]);
  74. }
  75. }
  76. }
  77. return 0;
  78. }
Success #stdin #stdout 0s 3472KB
stdin
2
a_b
ab_
aba_a
_baaa
stdout
1
2