牛客网 玛雅人的密码(BFS、清华机试)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sunlanchang/article/details/88553382

题目描述

玛雅人有一种密码,如果字符串中出现连续的2012四个数字就能解开密码。给一个长度为N的字符串,(2=<N<=13)该字符串中只含有0,1,2三种数字,问这个字符串要移位几次才能解开密码,每次只能移动相邻的两个数字。例如02120经过一次移位,可以得到20120,01220,02210,02102,其中20120符合要求,因此输出为1.如果无论移位多少次都解不开密码,输出-1。

输入描述:

输入包含多组测试数据,每组测试数据由两行组成。
第一行为一个整数N,代表字符串的长度(2<=N<=13)。
第二行为一个仅由0、1、2组成的,长度为N的字符串。

输出描述:

对于每组测试数据,若可以解出密码,输出最少的移位次数;否则输出-1。
示例1

输入

5
02120

输出

1

Description

使用BFS遍历所有的交换两个字符的可能,遍历过程中记录遍历的step,每遍历一种状态就判断是否满足结束的状态(包含2012)即可。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <map>
#include <queue>

using namespace std;

int cnt[3];
typedef pair<string, int> Node;
map<string, int> mapping; //记录已经访问过的状态

string str;
queue<Node> que; //BFS队列

bool isOk(string s)
{
    if (s.find("2012") != string::npos)
        return true;
    return false;
}
int main()
{
    int n;
    while (scanf("%d", &n) != EOF)
    {
        cin >> str;
        int len = str.size();
        memset(cnt, 0, sizeof(cnt));
        for (int i = 0; i < len; i++)
            cnt[str[i] - '0']++;
        if (cnt[0] < 1 || cnt[1] < 1 || cnt[2] < 2) //判断没有2012的情况
        {
            puts("-1");
            continue;
        }
        while (!que.empty()) //清空队列
            que.pop();
        mapping.clear();
        mapping[str] = 1;       //将初始的字符串设置为已经出现
        que.push(Node(str, 0)); //BFS队列中第一个入队元素
        int ans = -1;
        while (!que.empty())
        {
            Node p = que.front();
            string t = p.first;
            int step = p.second;
            que.pop();
            if (isOk(t)) //字符串包含2012停止搜索
            {
                ans = step;
                break;
            }
            for (int i = 0; i + 1 < len; i++) //搜索交换两个字符位置的情况
            {
                string tmp = t;
                swap(tmp[i], tmp[i + 1]);
                if (mapping.find(tmp) == mapping.end()) //交换字符后和自己不重合时,例如2200前两个字符交换会重合
                {                                       //就不会进入搜索中
                    mapping[tmp] = 1;                   //将交换字符后的状态加入到已经访问过的map中
                    que.push(Node(tmp, step + 1));      //交换字符后的状态入队继续搜索,并记录第几次交换字符
                }
            }
        }
        printf("%d\n", ans);
    }
    return 0;
}

参考:https://www.cnblogs.com/jasonJie/p/5881959.html

猜你喜欢

转载自blog.csdn.net/sunlanchang/article/details/88553382