【NOIp 2002】【BFS+STL】字串变换

描述

已知有两个字串 A ,B 及一组字串变换的规则(至多6个规则):
A1 >B1
A2 >B2
规则的含义为:在 A$中的子串 A1 B1 、A2 B2 …。
例如:A abcdB =’xyz’
变换规则为:
‘abc’->‘xu’ ‘ud’->‘y’ ‘y’->‘yz’
则此时,A B ,其变换的过程为:
‘abcd’->‘xud’->‘xy’->‘xyz’
共进行了三次变换,使得 A B

格式

输入格式

第一行为两个字符串,第二行至文件尾为变换规则
A B
A1B1 \
A2 B2 |-> 变换规则
… … /
所有字符串长度的上限为 20。

输出格式

若在 10 步(包含 10步)以内能将 A B ,则输出最少的变换步数;否则输出”NO ANSWER!”

代码

BFS…再加上那么一点点STL小技巧、

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <map>
#define INF 1000
using namespace std;

struct Trans{
    string a,b;
    Trans(const string &a,const string &b){
        this->a=a; this->b=b;
    }
};

int n=1,d[1000],ans=20;
string A,B;
string a,b;
vector<Trans> trans;
map<string,int> dic;

bool bfs(){
    queue<string> q;
    q.push(A); dic[A]=0;
    while(!q.empty()){
        const string temp=q.front(); q.pop();
        if(dic[temp]>10) return false;
        if(temp==B) {
            ans=dic[temp]; return true;
        }
        for(int i=0;i<(int)trans.size();i++){
            int pos=temp.find(trans[i].a);
            while(pos!=(int)string::npos){
                string t2(temp);
                t2.replace(pos,trans[i].a.length(),trans[i].b);
                if(dic.count(t2)==0) {
                    q.push(t2); dic[t2]=dic[temp]+1;
                }
                pos=temp.find(trans[i].a,pos+1);
            }
        }
    }
    return false;
}


int main(){
    freopen("in.txt","r",stdin);
    cin>>A>>B;
    while(cin>>a>>b) trans.push_back(Trans(a,b));
    if(bfs()) printf("%d",ans);
    else printf("NO ANSWER!");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值