luogu题解P1032字串变换--BFS+STL:string骚操作

题目链接

https://www.luogu.org/problemnew/show/P1032

分析

这题本来很裸的一个BFS,发现其中的字符串操作好烦啊。然后就翻大佬题解发现用STL中的string居然变得这么简洁!!!

各种string操作请看另一位大佬博客,写得很全啊:

https://www.cnblogs.com/rvalue/p/7327293.html#commentform

其实我们这题只用到两个相关函数:(S.find(string,pos))(S.substr())

前一个是朴素查找,后一个是子串替换,用法都在那个大佬博客中有

代码

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <string>
#include <queue>
#include <iostream>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/hash_policy.hpp>
#define ll long long 
#define ri register int
#define mkp make_pair
using namespace std;
using namespace __gnu_pbds;
template <class T>inline void read(T &x){
	x=0;int ne=0;char c;
	while(!isdigit(c=getchar()))ne=c=='-';
	x=c-48;
	while(isdigit(c=getchar()))x=(x<<3)+(x<<1)+c-48;
	x=ne?-x:x;return ;
}
const int maxn=25;
const int inf=0x7fffffff;
pair<string,string> pi[maxn],TMP;
int ans=0,cnt=0;
gp_hash_table <string,bool> g;
string A,B;
struct Dat{
	string p;
	int step;
	Dat(){;}
	Dat(string _p,int _s){p=_p;step=_s;}
}Tmp;
queue< Dat > q;
int main(){
	string a,b;
	int t,pos;
	std::ios_base::sync_with_stdio(0);
	cin.tie(0);
	cin>>A>>B;
	while(cin>>a>>b){
		pi[++cnt]=mkp(a,b);
	}
	q.push(Dat(A,0));
	g[A]=1;
	while(q.size()){
		Tmp=q.front();
		A=Tmp.p,t=Tmp.step;q.pop();
		if(A==B){
			ans=t;
			if(t<10){printf("%d
",t);}
			else puts("NO ANSWER");
			return 0;//break;
		}
		for(ri i=1;i<=cnt;i++){
			a=pi[i].first;
			pos=A.find(a);//返回查找串开头位置
			while(pos!=A.npos){
				b=A.substr(0,pos);//将前部分串复制下来
				b+=pi[i].second;//拼接串
				b+=A.substr(pos+a.size());//将后面的串接上去
				if(!g[b]){
					q.push(Dat(b,t+1));
					g[b]=1;
				}
				pos=A.find(a,pos+1);
			}
		}
	}
	puts("NO ANSWER");
	return 0;
}
原文地址:https://www.cnblogs.com/Rye-Catcher/p/9539424.html