跳到正文

题解

题解:P1032 [NOIP 2002 提高组] 字串变换

songyouyi约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年3月18日
收录
2025年12月12日
更新
2026年11月14日
篇幅
约 3 分钟
获赞
12
题目
P1032

版本

  1. v1当前

这题没啥难的,其实就一个爆搜而已。

蒟蒻一开始试了下 dfs,超时了可能是因为我太菜写不出正解,于是就想到了 bfs。大概就是每次枚举每条规则,看看能不能改,把更改后的状态入队就可以了。

注意:

  1. 一定要判重!不判重可能字串变换时会在一个环里一直绕。这里推荐使用 map 可以判重,这里相当于一个映射数组,如果没学过,可以理解成一个下标是任意类型的数组。

  2. 超过一定次数就退出,因为有可能一直可以变,也会卡死循环,比如当前是 aaaa\texttt a \texttt a \texttt a \texttt a,有规则 a\texttt a 可以变到 aa\texttt a \texttt a,这样就会一直往下变。

C++
#include<bits/stdc++.h>
using namespace std;
string s,t;
string bian[1010][2];
int tot;
map<string,bool> mp;
struct node
{
	string s;
	int d;
};//s代表当前字符串,d代表修改次数
void bfs()
{
	mp[s]=1;
	queue<node> q;
	q.push({s,0});
	while (!q.empty())
	{
		node ss=q.front();
		q.pop();
		if (ss.d>10)
		{
			continue;
		}//超过一定次数就退出
		if (ss.s==t)
		{
			printf("%d",ss.d);
			exit(0);
		}
		if (ss.d==10)
		{
			continue;
		}
		int sz=ss.s.size();
		for (int i=1;i<=tot;i++)
		{
			int sz0=bian[i][0].size(),sz1=bian[i][1].size();
			int last=-1;
			while (1)
			{
				int fd=ss.s.find(bian[i][0],last+1);//第一个开头字母位置
				if (fd==-1)
				{
					break;
				}
				int j=fd;
				last=fd;
				string tt;
				for (int k=0;k<j;k++)
				{
					tt+=ss.s[k];
				}
				for (int k=0;k<sz1;k++)
				{
					tt+=bian[i][1][k];
				}
				for (int k=j+sz0;k<sz;k++)
				{
					tt+=ss.s[k];
				}
				if (mp[tt])//判重
				{
					continue;
				}
				mp[tt]=1;
				q.push({tt,ss.d+1});
			}
		}
	}
}
int main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	cin>>s>>t;
	tot=0;
	while (cin>>bian[++tot][0])
	{
	//	getchar();
		cin>>bian[tot][1];
		//cout<<bian[tot][0]<<' '<<bian[tot][1]<<endl;
	}
	bfs();
	cout<<"NO ANSWER!";
	return 0;
}