题解 | #玛雅人的密码#

玛雅人的密码

https://www.nowcoder.com/practice/761fc1e2f03742c2aa929c19ba96dbb0

#include<bits/stdc++.h>
using namespace std;
string tmp;
int n;

void bfs(string t) {
    queue<pair<string, int> >q;
    q.push({t, 0});
    while (!q.empty()) {
        auto s = q.front();
        q.pop();
        //队列先进先出,第一个符合的一定是最小值
        if (s.first.find("2012") != -1) {
            cout << s.second;
            exit(0);
        }
        for (int i = 0; i < n - 1; i++) {
            swap(s.first[i], s.first[i + 1]);
            q.push({s.first, s.second + 1});
            swap(s.first[i], s.first[i + 1]);
        }
    }

}

int main() {

    cin >> n;
    cin >> tmp;
    //无论如何都有解,除非少于个数,故特判一下(虽然样例好像没有-1的情况)
    if (count(tmp.begin(), tmp.end(), '2') < 2 ||
            count(tmp.begin(), tmp.end(), '0') < 1  ||
            count(tmp.begin(), tmp.end(), '1') < 1 )
    {
        cout<<-1;
        return 0;
    } 
    bfs(tmp);//直接搜
    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务