社区讨论

双向bfs求助

P1032[NOIP 2002 提高组] 字串变换(疑似错题)参与者 2已保存回复 1

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
1 条
当前快照
1 份
快照标识符
@m2etjtlj
此快照首次捕获于
2024/10/18 22:22
去年
此快照最后确认于
2025/11/04 16:53
4 个月前
查看原帖
RT,#2#3RE
CPP
#include <bits/stdc++.h>
using namespace std;
typedef pair<string , int> P;
const int maxn = 1005;
string s , st , s1[maxn] , s2[maxn];
int cnt = 1;
map <P , bool>vis1 , vis2;
map <string , int>ans1 , ans2;
void Bfs()
{
	queue <P>q1 , q2;
	q1.push(P(s , 0)),q2.push(P(st , 0));
	while(q1.size() || q2.size())
	{
		string ss = q1.front().first;
		int p = q1.front().second;
//		cout << ss << " " << p << endl;
		q1.pop();
		if (ans2[ss])
		{
			if (ans2[ss] + p <= 10)cout << ans2[ss] + p;
			else cout << "NO ANSWER";
			exit(0);
		}
		ans1[ss]=p;
//		cout << ss << endl;
		for (int i = 1; i <= cnt; i++)
		{
//			cout << i << " ";
//			cout << q1.size() << endl;
			if (ss.find(s1[i]) != string::npos)
			{
				string tmp = ss;
				tmp.replace(ss.find(s1[i]) , s1[i].size() , s2[i]);
//				cout << tmp << endl;
				if (!vis1[P(tmp , p + 1)])q1.push(P(tmp , p + 1)),vis1[P(tmp , p + 1)]=1;
			}
		}
//		cout << endl;
		ss = q2.front().first , p = q2.front().second;
		q2.pop();
		if (ans1[ss])
		{
			if (ans1[ss] + p <= 10)cout << ans1[ss] + p;
			else cout << "NO ANSWER";
			exit(0);
		}
		ans2[ss]=p;
		for (int i = 1; i <= cnt; i++)
		{
			if (ss.find(s2[i]) != string::npos)
			{
				string tmp = ss;
				tmp.replace(ss.find(s2[i]) , s2[i].size() , s1[i]);
				if (!vis2[P(tmp , p + 1)])q2.push(P(tmp , p + 1)),vis2[P(tmp , p + 1)]=1;
			}
		}
	}
}
int main ()
{
	cin >> s >> st;
	s = s;
	while(cin >> s1[cnt] >> s2[cnt])s1[cnt++]=s1[cnt] , s2[cnt]=s2[cnt];
	cnt--;
	Bfs();
	return 0;
}

回复

1 条回复,欢迎继续交流。

正在加载回复...