题解 | #玛雅人的密码#

#include <iostream>

#include <queue>

#include <string>

using namespace std;

typedef pair<int, string> PII;

void DFS(string str){

    queue<PII> q;

    q.push({0, str});

    while(!q.empty()){

        auto t = q.front();

        q.pop();

        if (t.second.find("2012") != string::npos) {

            cout << t.first << endl;

            return;

        }

        for(int i = 0; i < t.second.length() - 1; i ++){

            swap(t.second[i], t.second[i+1]);

            q.push({t.first + 1, t.second});

            swap(t.second[i], t.second[i+1]);//恢复交换前的字符串,对后续字符进行交换

        }

    }

    cout << -1 << endl;

}

int main() {

    int n;

    string str;

    while(cin >> n >> str){

        DFS(str);

    }

    return 0;

}

全部评论

相关推荐

想顺利毕业的猕猴桃在看牛客:好几个月没面试了,腾讯留面评吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务