交换
2025-01-23 18:54:56
发布于:上海
#include<bits/stdc++.h>
using namespace std;
#pragma GCC optimize(3)
map<string,int> mp;//mp 存 key value
string a,b;
struct node{
string s;
int d;
};
int main(){
cin>>a;
b = "xiaomawang";
queue<node> q;
q.push({a,0});
mp[a]=0;//变成a这个数用了几次
while(q.size()){
node t = q.front();
q.pop();
string x = t.s;
int op = t.d;
if(x==b){
cout<<mp[b];
return 0;
}
int n = x.size();
for(int i=0;i<n-1;i++){
swap(x[i],x[i+1]);
if(mp.find(x) == mp.end() || mp[x]>op+1){
mp[x] = op+1;
q.push({x,mp[x]});
}
swap(x[i],x[i+1]);
}
}
cout<<-1;
return 0;
}
这里空空如也
有帮助,赞一个