NOIP2002提高组 字串变换

洛谷-题目-字串变换

使用C++的string,跑一遍BFS,就可以解决。唯一的问题是怎么判断某个字符串是否出现过??可以考虑一下C++的set和map。这里使用set。

    #include <cstdio>
    #include <string>
    #include <iostream>
    #include <set>
    using namespace std;
    string Begin,End;
    struct{
        string a,b;
    }Node[10];
    set<string> vis;
    int tot=0;
    string que[10000000];
    inline int bfs(){
        int cnt,head=1,tail=1,ans=0;
        que[1]=Begin;
        if(Begin==End)return 0;
        while(head<=tail){
            if(ans==10)return -1;
            cnt=0;
            ans++;
            for(register int i=head;i<=tail;i++){
                int len=que[i].length();
                for(register int j=0;j<tot;j++){
                    int len_Node=Node[j].a.length();
                    for(register int k=0;k+len_Node<=len;k++){
                        string cmp=que[i].substr(k,len_Node);
                        if(cmp==Node[j].a){
                            string wait=que[i].substr(0,k)+Node[j].b+que[i].substr(k+len_Node,len-(k+len_Node));
                            if(vis.count(wait))continue;
                            cnt++;
                            que[tail+cnt]=wait;
                            vis.insert(wait);
                            if(que[tail+cnt]==End)return ans;
                        }
                    }
                }
            }
            head=tail+1;
            tail+=cnt;
        }
        return -1;
    }
    int main() {
        cin>>Begin>>End;
        while(cin>>Node[tot].a>>Node[tot].b)tot++;
        int answer=bfs();
        if(answer!=-1)printf("%d\n",answer);
        else puts("NO ANSWER!");
        return 0;
    }

转载于:https://www.cnblogs.com/Neworld2002/p/8470863.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值