蒟蒻求助,dfs,样例都没过。。
查看原帖
蒟蒻求助,dfs,样例都没过。。
321647
阿炜楼主2022/11/19 10:08
#include<bits/stdc++.h>
using namespace std;
string A,B,a[30],b[30];
map<string,bool> ed; //判重
map<string,int> st; //存数
int n=1,ans=999999,k=2;
void dfs(string now,int x)
{
	if(x>k) return; //迭代加深,到到当前层数就返回
	if(now==B) {
		ans=min(ans,x);
		return;
	}
	if(ed[now]) { //剪枝
		if(x>=st[now]) return ;
	}
	ed[now]=1; //初始化当前层数的值
	st[now]=x;
	int loc=0;
	string change;
	for(int i=1; i<=n; ++i) {
		loc=-1;
		while(1) {
			loc=now.find(a[i],loc+1); //找到匹配字串的位置
			if(loc==-1) break;
			change=now;
			change.erase(loc,a[i].size()); //删除 s 中下标为 loc开始的len个字符
			change.insert(loc,b[i]);//在 s下标为 loc 的元素前插入 string 类型 s2
			dfs(change,x+1);
		}
	}
	return ;
}
int main()
{
	cin>>A>>B;
	while(cin>>a[n]>>b[n]) {
		n++;
	}
	n--;
	while(ans==999999) { //迭代加深
		dfs(A,0);
		ed.clear();      // 清理之前层数的数据
		st.clear();
		k++;             //增加层数
		if(k==11) break; //最多10层
	}
	if(ans=999999) {
		cout<<"NO ANSWER!"<<endl;
		return 0;
	}
	cout<<ans<<endl;
	return 0;
}
2022/11/19 10:08
加载中...