双向广搜-----字串变换

已知有两个字串 AA

, BB

及一组字串变换的规则(至多6个规则):A1A1

-> B1B1

A2A2

-> B2B2

…规则的含义为:在 AA

中的子串 A1A1

可以变换为 B1B1

、A2A2

可以变换为 B2B2

…。例如:AA

=’abcd’ BB

=’xyz’变换规则为:‘abc’->‘xu’ ‘ud’->‘y’ ‘y’->‘yz’则此时,AA

可以经过一系列的变换变为 BB

,其变换的过程为:‘abcd’->‘xud’->‘xy’->‘xyz’共进行了三次变换,使得 AA

变换为BB

。输入格式输入格式如下:AA

BB

A1A1

B1B1


A2A2

B2B2

|-> 变换规则
… … /所有字符串长度的上限为 20。 输出格式若在 10 步(包含 10步)以内能将 AA

变换为 BB

,则输出最少的变换步数;否则输出”NO ANSWER!”输入样例:abcd xyz
abc xu
ud y
y yz
输出样例:3

思路:从起点和终点同时搜索,哪头短便搜索哪头

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <unordered_map>
using namespace std;
const int N = 6;
int n;
string a[N], b[N];
int extend(queue <string>&q, unordered_map <string, int>&da, unordered_map <string, int>&db, string a[], string b[]){
     string t = q.front();
  q.pop();
   for (int i = 0; i < t.size(); i ++) 
      for (int j = 0; j < n; j ++)
    if (t.substr(i, a[j].size()) == a[j]){
     string state = t.substr(0, i) +b[j] + t.substr(i + a[j].size());
     if(db.count(state))   return da[t] + 1 + db[state];
     if(da.count(state))   continue;
     da[state] = da[t] + 1;
     q.push(state);
    } 
  return 11;
}
int bfs(string A,string B){
 queue <string> qa,qb;
 unordered_map <string, int> da,db;
 qa.push(A),      da[A] = 0;
 qb.push(B),      db[B] = 0;
  while(qa.size() && qb.size()){
  int t;
  if (qa.size() < qb.size())    t = extend(qa, da, db, a, b);
  else    t = extend(qb, db, da, b, a);
  if (t <= 10)    return  t;
 }
 return 11;
}
int main(){
 string A, B;
 cin >> A >> B;
 while (cin >> a[n] >> b[n])    n ++;
 int step = bfs(A, B);
 if (step > 10)     puts("NO ANSWER!");
 else               printf("%d\n", step);
 return 0;
}
  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值