跳到正文

题解

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

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

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟
题目
P1032

版本

  1. v1当前

BFS函数:bfs 函数使用队列来进行广度优先搜索。每次从队列中取出一个状态,尝试应用所有规则生成新的状态,并将这些新状态加入队列。如果找到目标状态 B,则返回当前步数。

规则应用:在每次状态转移时,使用 string::find 和 string::replace 来应用规则。

步数限制:如果步数超过 10 步,则停止搜索。

主函数:读取输入数据,调用 bfs 函数,并输出结果。

C++
#include <bits/stdc++.h>
using namespace std;
// 定义规则结构体
struct Rule {
	string from;
	string to;
};
// BFS函数,返回从A到B的最少步数,或者-1表示无法在10步内完成
int bfs(const string& A, const string& B, const vector<Rule>& rules) {
	queue<pair<string, int >> q; // 队列存储当前状态和步数
	q.push({A, 0});

	unordered_set<string> visited; // 记录已经访问过的状态
	visited.insert(A);

	while (!q.empty()) {
		auto cur = q.front();
		q.pop();

		string cu = cur.first;
		int steps = cur.second;

		if (cu == B) {
			return steps; // 找到目标状态,返回步数
		}

		if (steps >= 10) {
			continue; // 超过10步,跳过
		}

		// 尝试应用所有规则
		for (const auto& rule : rules) {
			size_t pos = cu.find(rule.from);
			while (pos != string::npos) {
				string newStr = cu;
				newStr.replace(pos, rule.from.length(), rule.to);

				if (visited.find(newStr) == visited.end()) {
					visited.insert(newStr);
					q.push({newStr, steps + 1});
				}

				pos = cu.find(rule.from, pos + 1); // 继续查找下一个匹配位置
			}
		}
	}
	return -1; // 无法在10步内找到目标状态
}

int main() {
	string a, b;
	cin >> a >> b;

	vector<Rule> rules;
	string from, to;
	while (cin >> from >> to) {
		rules.push_back({from, to});
	}

	int result = bfs(a, b, rules);

	if (result != -1)
		cout << result << endl;
	else
		cout << "NO ANSWER!" << endl;
	return 0;
}
原文