题解 | #玛雅人的密码#

玛雅人的密码

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

//采用广度优先遍历
#include "stdio.h"
#include "string"
#include "queue"
#include "map"
using namespace std;
struct TreeNode{
    string code;
    int sum;
};

int BFS_CODE(string str){
    queue<TreeNode> myQueue;//用于广度优先遍历
    map<string,bool> myMap;//用于识别字符串相同的TreeNode
    TreeNode node;
    node.code = str;
    node.sum = 0;
    myQueue.push(node);
    myMap[str] = true;
    while (!myQueue.empty()){
        TreeNode node2 = myQueue.front();
        myQueue.pop();
        string code = node2.code;int sum = node2.sum;
        int count = node2.code.find("2012");
        if (count != string::npos)
            return node2.sum;
        for (int i = 0; i < node2.code.size()-1; ++i) {
            swap(node2.code[i],node2.code[i+1]);
            node2.sum++;
            map<string,bool> ::iterator it = myMap.find(node2.code);
            if (it != myMap.end()){//map中已有此字符串
                swap(node2.code[i],node2.code[i+1]);//此处再交换是不让node2中的code改变
                node2.sum--;
                continue;
            }
            else{
                myQueue.push(node2);
                myMap[node2.code] = true;
                swap(node2.code[i],node2.code[i+1]);//与上面的再交换同理
                node2.sum--;
            }
        }
    }
    return -1;
}

int main(){
    int N;char buf[14]={};
    while (scanf("%d",&N)!=EOF){
        getchar();
        for (int i = 0; i < N; ++i) {
            scanf("%c",buf+i);
        }
        string str = buf;
        printf("%d\n", BFS_CODE(str));
    }
}

全部评论

相关推荐

头顶尖尖的程序员:我是26届的不太懂,25届不应该是找的正式工作吗?为什么还在找实习?大四还实习的话是为了能转正的的岗位吗
点赞 评论 收藏
分享
牛客83700679...:简历抄别人的,然后再投,有反馈就是简历不行,没反馈就是学历不行,多投多改只要技术不差机会总会有的
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-07 11:30
仁者伍敌:kpi都懒得刷了属于是
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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