洛谷PP1032 [NOIP2002 提高组] 字串变换

题目大意:

对于每个状态下的字符串,枚举可以替换的部分替换作为下一个新的状态。

说明/提示:

对于 100 100 100% 数据,保证所有字符串长度的上限为 20 20 20

思路/分析:

需要注意 替换的不一定是最开始匹配的子串,替换的还可能是后面的子串,比如这组样例:
a b c d e a b c d abcdeabcd abcdeabcd a b c d e e abcdee abcdee
a b c d e abcd e abcde
替换的是后面的 a b c d abcd abcd,所以我们在枚举某个替换规则时,我们要用一个 w h i l e while while 循环,配合着 f i n d find find 函数第二个参数,从上一个子串的下一位置 i d x + 1 idx + 1 idx+1 寻找,避免一直找的是第一个。

代码:

#include <bits/stdc++.h>
using namespace std;
struct node {
    string str;
    int step;
    node(string ss, int ste) {
        str = ss, step = ste;
    }
};
string a, b;
pair<string, string> s[10];
int cnt, ans = 1000000;
queue<node> q;
void bfs() {
    while (!q.empty()) {
        node now = q.front();
        q.pop();
        if (now.step > 10)
            continue;
        if (now.str == b) {
            ans = now.step;
        }
        for (int i = 0; i < cnt; i++) {
            int idx = -1;
            while (1) {
                string ss = now.str;
                idx = ss.find(s[i].first, idx + 1);
                if (idx == -1){
                    break;
                }
                ss.replace(idx, s[i].first.size(), s[i].second);
                if(ss == b){
                    ans = now.step + 1;
                    return;
                }
                q.push(node(ss, now.step + 1));
            }
        }
    }
}
int main() {
    cin >> a >> b;
    while (cin >> s[cnt].first && cin >> s[cnt++].second);
    q.push(node(a, 0));
    bfs();
    if(ans != 1000000){
        cout << ans;
    }else{
        cout << "NO ANSWER!";
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值