洛谷P1032

题目
字符串的题坑是真的多,感觉这种筛选是有bug的,不过数据比较弱还是过了,先存着,以后有能力再优化。
这道题想挖坑太容易了。

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

struct Node{
	string str;
	int step;
};
string A, B;
string rule_A[6], rule_B[6];
int cnt_rule = 0;
queue<Node> que;

int bfs()
{
	while (true){
		Node head = que.front();
		if (head.str == B || head.step >= 11)
			break;
		que.pop();
		int idx;
		for (int i = 0; i < cnt_rule; i++){
			Node tmp;
			if ((idx = head.str.find(rule_A[i])) != string::npos){
				tmp.str = head.str;
				tmp.str.replace(idx, rule_A[i].size(), rule_B[i]);
				tmp.step = head.step + 1;
				que.push(tmp);
			}
		}
	}
	if (que.front().step == 11)
		return 0;
	else
		return que.front().step;	
}
int main()
{
	cin >> A >> B;
	while (cin >> rule_A[cnt_rule] >> rule_B[cnt_rule]){
		cnt_rule++;
	}
    for (int i = 0; i < A.size() && i < B.size(); i++){//筛掉重复部分
		if (A.size() == 1 || B.size() == 1)
			break;
		if (A[i] == B[i]){
			A.erase(i, 1);
			B.erase(i, 1);
			i = -1;
		}
	}
	Node start;
	start.str = A;
	start.step = 0;
	que.push(start);
	int ans = bfs();
	if (ans)
		cout << ans << endl;
	else
		cout << "NO ANSWER!" << endl;	
	return 0;
}
发布了24 篇原创文章 · 获赞 0 · 访问量 369

猜你喜欢

转载自blog.csdn.net/weixin_43971049/article/details/103742297