POJ-3803(模拟Sed,BFS)

本文分析了POJ 3803题目的解题思路,通过BFS算法解决字符串替换问题。介绍了如何使用C++实现字符串的查找与替换,并通过层级遍历来寻找最短路径。

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

题目:http://poj.org/problem?id=3803

分析:数据量不大,直接BFS即可


#include <iostream>
#include <string>
#include <queue>
#include <set>
using namespace std;

int n;
string a[10], b[10], s, t;

bool sub(string& p, const string& a, const string& b)
{
	size_t plen = p.size(), alen = a.size(), blen = b.size(), i = p.find(a, 0);
	if(i == string::npos) return false;

	for(; i != string::npos; i = p.find(a, i+blen)){
		if(plen - alen + blen > t.size()) return false;
		p.replace(i, alen, b);
	}
	return true;
}
int bfs()
{
	if(s == t) return 0;

	queue<string> Q;
	set<string> R;

	Q.push(s);
	R.insert(s);
	int level = 0;
	while(!Q.empty()){
		++level;
		for(int cnt = Q.size(); cnt; --cnt){
			for(int i = 0; i < n; ++i){
				string p = Q.front();
				if(!sub(p, a[i], b[i]) || R.count(p)) continue;
				if(p == t) return level;
				Q.push(p);
				R.insert(p);
			}
			Q.pop();
		}
	}
	return -1;
}

int main()
{
	while(cin >> n, n){
		for(int i = 0; i < n; ++i) cin >> a[i] >> b[i];
		cin >> s >> t;
		cout << bfs() << "\n";
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值