BFS,WA只得了20分求助
查看原帖
BFS,WA只得了20分求助
528430
FiraCode楼主2022/10/26 08:39
#include <bits/stdc++.h>
using namespace std;
int n;
string s;
map<string, int> dist;
map<string, bool> st;
void bfs()
{
	queue<string> q;
	q.push(s);
	dist[s] = 0;
	st[s] = true;
	while (q.size())
	{
		auto t = q.front();
		q.pop();
		if (!t.size()) continue;
        //交换
		for (int i = 0; i < t.size(); ++i)
			for (int j = i + 1; j < t.size(); ++j)
			{
				string temp = t;
				swap(temp[i], temp[j]);
				if (!st[temp])
				{
					dist[temp] = dist[t] + 1;
					st[temp] = true;
					q.push(temp);
				}
			}
            //删除
		for (int i = 0; i < t.size(); ++i)
		{
			string temp = t;
			temp.erase(i, 1);
			if (!st[temp])
			{
				dist[temp] = dist[t] + 1;
				st[temp] = true;
				q.push(temp);
			}
		}
        //插入
		for (int i = 0; i < t.size() - 1; ++i)
		{
			for (char j = t[i] + 1; j < t[i + 1]; ++j)
			{
				string temp = t;
				temp.insert(i, 1, j);
				if (!st[temp] && temp.size() <= s.size())
				{
					dist[temp] = dist[t] + 1;
					st[temp] = true;
					q.push(temp);
				}
			}
		}
	}
}
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(NULL), cout.tie(NULL);
	cin >> s;
	cin >> n;
	bfs();
	for (int i = 1; i <= n; ++i)
	{
		string a;
		cin >> a;
		if (!st[a]) cout << -1 << endl;
		else cout << dist[a] << endl;
	}
	return 0;
}
2022/10/26 08:39
加载中...