双向bfs P1032 字串变换

这篇文章讨论了解决一个字符串变换问题的C++代码,利用BFS算法和哈希表来寻找从给定字符串A到字符串B的最短转换路径。作者提供了详细解释和代码片段,展示了如何在有限步骤内实现字符串的替换操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

传送门icon-default.png?t=N7T8https://www.luogu.com.cn/problem/P1032

找一个最短方案,考虑用bfs(没试过单向,但是系数很大)

更详细的解答

下面是代码理解(注释版)

// Problem: 
//     P1032 [NOIP2002 提高组] 字串变换
//   
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P1032
// Memory Limit: 125 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include<iostream>
#include<string>
#include<unordered_map>//哈希表 
#include<queue>
using namespace std;
string A,B;
string a[6],b[6];//方案
int len;

int extend(queue<string>&q,unordered_map<string,int> &ha,unordered_map<string,int> 
&hb,string a[],string b[]){
	int m=q.size();//每次只扩展一层
	while(m--){
		auto t=q.front();q.pop();
		for(int i=0;i<len;++i){//枚举方案
			for(unsigned int j=0;j<t.size();++j){//枚举起始位置
				if(t.substr(j,a[i].size())==a[i]){
					string ss=t.substr(0,j)+b[i]+t.substr(j+a[i].size());//字符串
					if(ha.count(ss)) continue;//如果这里之前有跳过
					if(hb.count(ss)) return ha[t]+hb[ss]+1;//对面之前有就返回答案
					ha[ss]=ha[t]+1;//更新
					q.push(ss); //入列
				}
			}
		}
	}
	return 11;
}

int bfs(){
	unordered_map<string,int> ha,hb;
	queue<string> qa,qb;
	qa.push(A);qb.push(B);
	ha[A]=0,hb[B]=0;//别忘,不然count找不到
	int t=10;
	while(t--){
		int ans;
		if(qa.size()<qb.size()) ans=extend(qa,ha,hb,a,b);
		else ans=extend(qb,hb,ha,b,a);//反着传,因为两边对应关系不同
		if(ans<=10) return ans;
	}
	return 11;
}

int main(){
    cin>>A>>B;
    while(cin>>a[len]){
    	cin>>b[len++];//len记录个数
    }
    if(bfs()<=10) cout<<bfs()<<endl;
    else cout<<"NO ANSWER!";
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值