题目大意:
s
<
1
e
5
s <1e5
s<1e5
分析:
显然bfs每次第一个碰到的是答案,
草稿纸上粗略算了一下,发现一个
s
s
s 的产物并不会很多,
b
f
s
bfs
bfs过程用
s
e
t
set
set跟
m
a
p
map
map维护,对询问直接查询即可
代码:
#include<bits/stdc++.h>
using namespace std;
string s, t;
map<string, int>dis;
set<string>vis;
int len, m;
queue<string>q;
void bfs() {
q.push(s);
vis.insert(s);
dis[s] = 0;
while (!q.empty()) {
string u = q.front(); q.pop();
for (int i = 0; i < u.length(); i++)
for (int j = i + 1; j < u.length(); j++) {
string v = u;
swap(v[i], v[j]);
if (!vis.count(v)) {
dis[v] = dis[u] + 1;
vis.insert(v);
q.push(v);
}
}
if (u.length() > 1) {
for (int i = 0; i < u.length(); i++) {
string v = u;
v.erase(i, 1);
if (!vis.count(v)) {
dis[v] = dis[u] + 1;
vis.insert(v);
q.push(v);
}
}
}
if (u.length() < len && u.length() >= 2) {
for (int i = 0; i < u.length() - 1; i++)
if (u[i + 1] - u[i] > 1) {
for (char o = u[i] + 1; o < u[i + 1]; o++) {
string v = u.substr(0, i + 1) + o + u.substr(i + 1, u.length() - i - 1);
if (!vis.count(v)) {
dis[v] = dis[u] + 1;
vis.insert(v);
q.push(v);
}
}
}
}
}
}
int main() {
// freopen("data.in", "r", stdin);
cin >> s;
len = s.length();
bfs();
// for (set<string>::iterator it = vis.begin(); it != vis.end(); it++) cout << * it <<endl;
cin >> m;
while (m--) {
cin >> t;
if (vis.count(t)) printf("%d\n", dis[t]); else puts("-1");
}
return 0;
}