洛谷 P1032 字串变换

洛谷 P1032 字串变换

题目:

题解:

  • 坑点重重... ...
  1. 要用bfs (第一个搜到的就是答案,节约时间)
  2. 一个字符串可能对应着许多不同的字符串

  3. bfs模版里pop时vis数组也要相应的清零
  4. 用map去重
  5. 记得无解的情况
  6. 一个串中可能有多个可替换串

#include <iostream>
#include <cstdio>
#include <string>
#include <map>
#include <queue>
#include <cstdlib>
using namespace std;

struct Cha {string x, y;} cha[10];
struct Obj {string s; int step;};
int n;
string a, b;
map<string, string> mp;
map<string, bool> vis;

void bfs()
{
    queue<Obj> que;
    Obj tmp;
    tmp.s = a, tmp.step = 0;
    que.push(tmp), vis[a] = 1;
    while(!que.empty())
    {
        Obj now = que.front();  que.pop();
        for(int i = 1; i <= n; i++)
        {
            int last = 0;
            while(1)
            {
                string t = cha[i].x;
                int pos = now.s.find(t, last);
                if(pos == -1) break;
                else last = pos + 1;
                tmp.s = now.s.substr(0, pos) + cha[i].y + now.s.substr(pos + t.size(), now.s.size() - (pos + t.size()));
                tmp.step = now.step + 1;
                if(tmp.step > 10) continue;
                if(tmp.s == b) {cout << tmp.step; exit(0);}
                if(!vis[tmp.s])
                {
                    vis[tmp.s] = 1;
                    que.push(tmp);
                }
            }
        }
    }
}

int main()
{
    freopen("P1032.in", "r", stdin);
    freopen("P1032.out", "w", stdout);
    
    cin >> a >> b;
    while(cin >> cha[++n].x) cin >> cha[n].y;
    bfs();
    cout << "NO ANSWER!";
    return 0;
}

转载于:https://www.cnblogs.com/BigYellowDog/p/11167427.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值