题解 | #玛雅人的密码#

玛雅人的密码

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

全部评论

相关推荐

明天不下雨了:我靠2022了都去字节了还什么读研我教你****:你好,本人985电子科大在读研一,本科西南大学(211)我在字节跳动实习过。对您的岗位很感兴趣,希望获得一次投递机会。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务