Tsinghua computer test - Mayan password (wide search)

Topic description

The Mayans have a password that can be unlocked if four consecutive numbers of 2012 appear in the string. Given a string of length N, (2=<N<=13), the string contains only three numbers of 0, 1, and 2. Ask this string to shift several times to unlock the password, each time only Can move two adjacent numbers. For example, after 02120 is shifted once, 20120, 01220, 02210, and 02102 can be obtained, of which 20120 meets the requirements, so the output is 1. If the password cannot be unlocked no matter how many times it is shifted, output -1.

Enter description:

The input contains multiple sets of test data, each consisting of two rows.
The first line is an integer N, representing the length of the string (2<=N<=13).
The second line is a string of length N consisting of only 0, 1, and 2.

Output description:

For each set of test data, if the password can be solved, output the minimum number of shifts; otherwise, output -1.
Example 1

enter

5
02120

output

1

Problem solving ideas

The key point of this problem is the exchange of positions. All possible outcomes are formed by exchange, and the minimum number of exchanges required is also sought. So starting from the number of exchanges, you can think about the problem like this: 
you get a string every time you exchange it. If it has already appeared, you don't need to consider it. If it has not appeared, then judge whether "2012" has appeared. If there is, the number of exchanges is the number of exchanges of the original string plus 1.

code

#include <iostream>
#include <cmath>
#include <map>
#include <string>
#include <queue>
using namespace std;

string swap(string s,int i)
{
    string ans = s;
    char temp = s[i];
    ans[i] = ans[i + 1];
    ans[i + 1] = temp;
    return ans;
}

intmain()
{
    int len;
    string str;
    string target = "2012";
    while(cin >> len >> str)
    {
        int years = 0;
        map<string,int> mp;
        queue<string> q;
        mp [str] = 0;
        q.push(str);
        while(!q.empty())
        {
            string temp = q.front();
//            cout << temp << endl;
            q.pop();
            if(temp.find(target) != -1)
            {
                ans = mp[temp];
                break;
            }
            else
            {
                for(int i = 0;i < len - 1;i++)
                {
                    string now = swap(temp,i);
                    if(mp.find(now) == mp.end())
                    {
                        mp[now] = mp[temp] + 1;
                        q.push(now);
                    }
                }
            }
        }
        cout << ans << endl;
    }
    return 0;
}

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324382083&siteId=291194637