题解 | #[NOIP2002]字串变换#

[NOIP2002]字串变换

https://ac.nowcoder.com/acm/problem/16742

#include <iostream>
#include <map>
#include <queue>

using namespace std;

int n = 1;
string s, t;
string a[10], b[10];

map <string, int> A, B;
queue <string> qup, qbl;

int bfs() {
    int step = 0;

    qup.push(s), A[s] = 0;
    qbl.push(t), B[t] = 0;

    while(++ step <= 5) {
        while(A[qup.front()] == step - 1) {
            string t = qup.front();

            for(int i = 1; i <= n; i++) {
                int pos = 0;        //开始寻找a[i]的位置

                while(pos < t.size()) {
                    if(t.find(a[i], pos) == t.npos) break;

                    string tem = t;
                    tem.replace(tem.find(a[i], pos), a[i].size(), b[i]);

                    if(A.find(tem) != A.end()) {pos ++; continue;}
                    if(B.find(tem) != B.end()) return step * 2 - 1;

                    qup.push(tem), A[tem] = step, pos ++;
                }
            }

            qup.pop();
        }

        while(B[qbl.front()] == step - 1) {
            string t = qbl.front();

            for(int i = 1; i <= n; i++) {
                int pos = 0;

                while(pos < t.size()) {
                    if(t.find(b[i], pos) == t.npos) break;

                    string tem = t;
                    tem.replace(tem.find(b[i], pos), b[i].size(), a[i]);

                    if(B.find(tem) != B.end()) {pos ++; continue;}
                    if(A.find(tem) != A.end()) return step * 2;

                    qbl.push(tem), B[tem] = step, pos ++;
                }
            }

            qbl.pop();
        }
    }

    return -1;
}

int main() {
    cin >> s >> t;

    while(cin >> a[n] >> b[n]) n++;

    int ans = bfs();

    if(ans == -1) cout << "NO ANSWER!";
    else cout << ans;

    return 0;
}

需要注意本题应使用双向bfs,否则仅使用单向bfs会有mle/tle的问题
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-03 17:30
点赞 评论 收藏
分享
06-26 17:24
已编辑
宁波大学 Java
迷失西雅图:别给,纯kpi,别问我为什么知道
点赞 评论 收藏
分享
自学java狠狠赚一...:骗你点star的,港卵公司,记得把star收回去
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 14:00
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务