zoukankan      html  css  js  c++  java
  • 九度 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;
    }
  • 相关阅读:
    洛谷P2345 奶牛集会
    洛谷P3531 [POI2012]LIT-Letters
    codevs 4163 hzwer与逆序对
    各种读入方式速度比较
    洛谷P1420 最长连号
    TCPDump:捕获并记录特定协议 / 端口
    linux下抓取网页快照
    Pro Android 4 第五章 理解Intent
    UpdatePanel和jQuery不兼容
    RAC 11.2.0.4 安装 遇到 INS-06001
  • 原文地址:https://www.cnblogs.com/xinsheng/p/3587026.html
Copyright © 2011-2022 走看看