九度 1482:玛雅人的密码(BFS)

题目描述:

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

 

思路

1. 朴素 BFS 可解

2. 看了下题目来源, 2012 清华机试, 唔, 模拟, 数学, 动规, 三题一个小时. 当你考清华一同学向我描述清华的的机试状况. 

 

代码

#include <iostream>
#include <stdio.h>
#include <string>
#include <math.h>
#include <deque>
#include <memory.h>
using namespace std;

string str;
int N;

bool visited[1600000];

bool match(const string &str1) {

    for(int i = 0; i <= N-4; i ++) {
        if(str1.substr(i, 4) == "2012")
            return true;
    }
    return false;
}

int hash_func() {
    int res = 0;
    for(int i = 0; i < N; i ++)
        res = res*3+str[i]-'0';
    return res;
}

int main() {
    while(scanf("%d", &N) != EOF) {
        cin >> str;
        memset(visited, 0, sizeof(visited));

        deque<string> record;
        record.push_back(str);
        int cur_lel = 1, nxt_lel = 0, ret = 0;
        bool found = false;

        while(!record.empty()) {
            string cur = record.front();
            record.pop_front();
            cur_lel --;

            if(match(cur)) {
                found = true;
                cout << ret << endl;
                break;
            }

            for(int i = 0; i < N-1; i ++) {
                swap(str[i], str[i+1]);
                int hash_val = hash_func();
                if(!visited[hash_val]) {
                    visited[hash_val] = true;
                    record.push_back(str);
                    nxt_lel ++;
                }
                swap(str[i], str[i+1]);
            }

            if(cur_lel == 0) {
                cur_lel = nxt_lel;
                nxt_lel = 0;
                ret ++;
            }

        }
        if(!found)
            cout << -1 << endl;
    }
    return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值