算法提高之字串变换

算法提高之字串变换

  • 核心思想:双向广搜

    • 双向bfs 建立两个队列 一起bfs到中间态
cpp 复制代码
  #include <iostream>
  #include <cstring>
  #include <algorithm>
  #include <queue>
  #include <unordered_map>
  
  using namespace std;
  const int N = 6;
  
  int n;
  string A,B;
  string a[N],b[N];
  
  int extend(queue<string>& q, unordered_map<string, int>&da, unordered_map<string, int>& db, 
      string a[N], string b[N])
  {
      int d = da[q.front()];  //确定当前层数
      while(q.size() && da[q.front()] == d)  //如果是同一层的就搜
      {
          auto t = q.front();
          q.pop();
           
          for(int i=0;i<n;i++)  //遍历所有规则
          {
              for(int j=0;j<t.size();j++)
              {
                  if(t.substr(j,a[i].size()) == a[i])  //有相应的子串
                  {
                      //构造新的字符串
                      string r = t.substr(0,j) + b[i] + t.substr(j+a[i].size());
                      if(db.count(r)) return da[t] + db[r] + 1;  //如果b中已经搜到过
                      if(da.count(r)) continue;
                      da[r] = da[t] + 1;
                      q.push(r);
                  }
              }
          }
      }
      return 11;
  }
  int bfs()
  {
      if(A == B) return 0;
      queue<string> qa,qb;
      unordered_map<string,int> da,db;
      
      qa.push(A), qb.push(B);
      da[A] = db[B] = 0;
      int step = 0;  //记录步数 如果超过10 直接return -1
      while(qa.size() && qb.size())
      {
          int t;
          //优先扩展长度短的那个
          if(qa.size()<qb.size()) t = extend(qa,da,db,a,b);  //注意规则是a->b
          else t = extend(qb,db,da,b,a);  //规则是b->a 反向
          
          if(t <= 10) return t;  //没找到之前会返回一个>10的数
          if(++ step == 10) return -1;
      }
      return -1;
  }
  int main()
  {
      cin>>A>>B;
      while(cin>>a[n]>>b[n]) n++;
      
      int t = bfs();
      if (t == -1) puts("NO ANSWER!");
      else cout << t << endl;
  
  }
相关推荐
Fuyo_111938 分钟前
C++ AVL树保姆级详解:从平衡因子到四大旋转机制
java·c++·算法
jktantan1 小时前
每个节点 41 字节:把一棵百万节点树拆进 14 个 typed array
前端·javascript·vue.js·算法·typescript
揽星河..1 小时前
【C语言】猜数字游戏
c语言·算法·游戏
LabVIEW开发2 小时前
CTM-3 红外测温仪 + LabVIEW 温度怎么测?
算法·labview·测试·labview程序
纪念 2292 小时前
C++算法(六)
开发语言·c++·算法
Dumbness3 小时前
UIA 读微信群消息没有 id,怎么判断哪条是新的:后缀对齐在翻历史和撤回时整屏重报
python·算法
taka3 小时前
从 24x 到 141x:我用纯 Python 零依赖项目,扒开了 GPU 加速的性能黑洞
算法
UIU1144 小时前
P16237 [蓝桥杯 2026 省 B] 应急布线
数据结构·c++·算法·蓝桥杯
旖旎夜光4 小时前
LeetCode 315: 算右侧小于当前元素的个数(归并排序) —— 题解
c++·学习·算法·leetcode·排序算法
像风一样自由20204 小时前
2.如何用FastAPI把一个Python算法封装成HTTP服务
python·算法·fastapi