题解 | #玛雅人的密码#

玛雅人的密码

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

#include<iostream>
#include<cstdio>
#include<queue>
#include<string>
using namespace std;
struct status {
    string str;
    int time;
    status() {}
    status(string s, int t) :str(s), time(t) {}
};
string swap(string s, int a, int b) {
    string str = s;
    str[a] = s[b];
    str[b] = s[a];
    return str;
}
int BFS(string str) {
    queue<status> myQueue;
    myQueue.push(status(str, 0));
    while (!myQueue.empty()) {
        status current = myQueue.front();
        myQueue.pop();
        if (current.str.find("2012") != string::npos) return current.time;
        else {
            for (int i = 0; i < str.size() - 1; ++i) myQueue.push(status(swap(current.str, i, i + 1), current.time + 1));
        }
    }
    return -1;
}
int main() {
    int n, count_0, count_1, count_2;
    string str;
    while (cin>>n>>str) {
        count_0 = count_1 = count_2 = 0;
        for (int i = 0; i < n; ++i) {
            if (str[i] == '0')++count_0;
            else if (str[i] == '1')++count_1;
            else ++count_2;
        }
        if (count_0 < 1 || count_1 < 1 || count_2 < 2) printf("%d\n", -1);
        else {
            printf("%d\n", BFS(str));
        }
    }
    return 0;
}

全部评论

相关推荐

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