【题解】luogu p1032 字串变换

总结:
1.bfs的模板没有掌握好

2.string s 的时候可以用s[m]=x 将s字符串中的m位置的字符改变成x字符

 

一道简单的bfs

#include<bits/stdc++.h>
using namespace std;
string s1, s2;
string a[10], b[10];
int cnt = 1, m;
queue <string> q;
queue <int> num;
map <string, int> mapp;

int bfs()
{
    string s, ss;
    while(q.empty() == 0 && q.front() != s2 && num.front() <= 10)
    {
        if(mapp[q.front()] == 1)
        {
            q.pop();
            num.pop();
            continue;
        } 
        mapp[q.front()] = 1;
        for(int i = 1; i <= cnt; i++)
        {
            s = q.front();
            while(1)
            {
                m = s.find(a[i]);
                if(m == -1) break;
                ss = q.front();
                ss.replace(m, a[i].size(), b[i]);
                q.push(ss);
                num.push(num.front()+1);
                s[m] = '.';
            }
        }
        q.pop();
        num.pop();
    } 
    if(q.empty() == 1 || num.front() > 10) return -1;
    else return num.front();
}

int main()
{
    cin >> s1 >> s2;
    while(cin >> a[cnt] >> b[cnt]) cnt++;
    cnt--;
    q.push(s1);
    num.push(0);
    int ans = bfs();
    if(ans == -1)
    {
        cout << "NO ANSWER!";
        return 0;
    }
    else cout << ans;
    return 0;
} 

 

转载于:https://www.cnblogs.com/lovezxy520/p/11484480.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值