题解 | #玛雅人的密码#

玛雅人的密码链接

#include <cstdio>
#include <iostream>
#include <string>
#include <queue>
#include <set>
using namespace std;

struct node{
    int step;
    string str;
    node(int st,string s): step(st),str(s){}
};
set<string> inq;    //用来标记字符串是否入过队了,访问过则有inq.find(str)!=inq.end()
 
void BFS(string origin){
    queue<node> q;
    q.push(node(0,origin));
    inq.insert(origin);
    while(!q.empty()){
        node cur = q.front();
        q.pop();
        if(cur.str.find("2012")!=string::npos){
            cout<<cur.step<<endl;
            return;
            }
        for(int i = 1;i<cur.str.length();i++){
            string s = cur.str;
            char temp = s[i];
            s[i] = s[i-1];
            s[i-1] = temp;
            if(inq.find(s)==inq.end()) {
                q.push(node(cur.step+1,s));
                inq.insert(s);}
        }
    }
    cout<<"-1"<<endl;
}
int main(){
    int N;
    string str;
    while(cin>>N>>str){
        if(N<4)
            cout<<"-1"<<endl;
        else
            BFS(str);
    }
    return 0;
}

全部评论

相关推荐

06-18 13:28
已编辑
门头沟学院 Web前端
爱睡觉的冰箱哥:《给予你300的工资》,阴的没边了
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-07 13:35
虽然不怎么光彩,经过这件事,可能我真的要去认同“面试八股文早该淘汰!不会用AI作弊的程序员=新时代文盲!”这句话了
HellowordX:Ai的出现是解放劳动力的,不是用来破坏公平竞争环境的,这样下去,轻则取消所有线上面试,严重了会影响整个行业对所有人产生影响,企业会拉高入职考核各种离谱考核会层出不穷
你找工作的时候用AI吗?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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