题解 | #玛雅人的密码#

玛雅人的密码

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);
        }
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 15:37
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 17:10
什么素质,我请问呢,要掉小珍珠了。。。又憋屈又生气
Steven267:这不喷回去?花钱是大爷,记住这个道理
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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