BFS,但只有20分
查看原帖
BFS,但只有20分
955580
LOSpace楼主2024/1/26 08:49

求助。

#include<bits/stdc++.h>

using namespace std;

typedef pair<string, int> node;
unordered_map<string, int> mp;
string s, t;
int m, Len;

void bfs() {
	queue<string> q;
	q.push(s), mp[s] = 0;
	
	while (!q.empty()) {
		string now = q.front(); q.pop();
		
		int len = now.size(), step = mp[now] + 1;
		
		for (int i = 0; i < len - 1; i ++)
			for (int j = i + 1; j < len; j ++) {
				string cur = now; swap(cur[i], cur[j]);
				if (!mp[cur]) q.push(cur), mp[cur] = step;
			}
		
		if (len == 1) continue;
		for (int i = 0; i < len; i ++) {
			string cur = now; cur.erase(i, 1);
			if (!mp[cur]) q.push(cur), mp[cur] = step;
		}
		
		if (len == Len) continue;
		for (int i = 0; i + 1 < len; i ++) {
			int j = i + 1;
			for (char c = now[i] + 1; c < now[j]; c ++) {
				string cur = now; cur.insert(i, 1, c);
				if (!mp[cur]) q.push(cur), mp[cur] = step;
			}
		}
	}
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	cout.tie(nullptr);
	
	cin >> s >> m; Len = s.size();
	
	bfs();
	
	while (m --) {
		cin >> t;
		if (mp.count(t)) cout << mp[t] << '\n';
		else cout << "-1\n";
	}
	return 0;
}
2024/1/26 08:49
加载中...