题解 | #玛雅人的密码#

玛雅人的密码

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

//BFS真的很简单
#include <iostream>
#include <queue>
using namespace std;

struct State{
    string str;
    int count;
    State(string str,int count): str(str),count(count){}
};


void BFS(string s,int n)
{
    queue<State> q;
    q.push(State(s,0));
    while(!q.empty())
    {
        State current=q.front();
        q.pop();
        int found=current.str.find("2012");
        if(found!= string::npos)
        {
            cout<<current.count<<endl;
            break;
        }
        for(int i=0;i<n-1;i++)
        {
            State nextstate=current;
            nextstate.count++;
            nextstate.str[i]=current.str[i+1];
            nextstate.str[i+1]=current.str[i];
            q.push(nextstate);
        }
    }
}


int main() {
    int n;
    while (cin >> n) { 
        string s;cin>>s;
        int s2=0,s0=0,s1=0;
        for(int i=0;i<s.size();i++)
        {
            if(s[i]==0+'0')s0++;
            else if(s[i]==1+'0')s1++;
            else s2++;

        }
        if(s2<2||s1<1||s0<1)cout<<"-1"<<endl;
        else{
            BFS(s,n);
        }
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-07 13:47
机械打工仔:你自己匿名可以,这么好的公司就别给它匿名了
点赞 评论 收藏
分享
05-27 14:57
西北大学 golang
强大的社畜在走神:27届真不用急,可以搞点项目、竞赛再沉淀沉淀,我大二的时候还在天天打游戏呢
投递华为等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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