题目1482:玛雅人的密码

#include <iostream>
#include <cstring>
#include <map>
#include <algorithm>
#include <string>
#include <queue>
using namespace std;
 
struct mPair
{
    string s;
    int i;
    mPair(string sInput, int iInput)
    {
        s = sInput;
        i = iInput;
    }
};
bool has2012(string input)
{
    for(int i = 0 ; i < input.size()-3 ; i++)
    {
        if(input.substr(i,4)=="2012")
        {
            return true;
        }
    }
    return false;
}
 
int main()
{
    int N = 0 ;
    string input;
    while(cin >> N)
    {
        cin>>input;
        if(N<4)
        {
            cout<<-1<<endl;
            continue;;
        }
        bool flag1=false, flag2 = false, flag0 = false;
        for(int i = 0 ; i < N ; i++)
        {
            if(input[i] == '1')
            {
                flag1=true;
            }
            else if(input[i] == '2')
            {
                flag2=true;
            }
            else
            {
                flag0=true;
            }
        }
        if(!(flag1&&flag2&&flag0))
        {
            cout<<-1<<endl;;
            continue;
        }
        if(has2012(input))
        {
            cout<<0<<endl;
            continue;
        }
        queue<mPair> saves;
        map<string,int> judge;
        saves.push(mPair(input,0));
        bool flag = false;
        while(!saves.empty() && !flag)
        {
            mPair curr = saves.front();
            saves.pop();
            for(int i = 0 ; i < N-1 ; i++)
            {
                string temp = curr.s;
                char cTemp = temp[i];
                temp[i] = temp[i+1];
                temp[i+1] = cTemp;
                if(judge.find(temp) == judge.end())
                {
                    if(has2012(temp))
                    {
                        cout<<curr.i + 1<<endl;
                        flag = true;
                        break;
                    }
                    else
                    {
                        saves.push(mPair(temp, curr.i+1));
                        judge[temp] = 1;
                    }
                }
            }
        }
        if(!flag)
        {
            cout<<-1<<endl;
        }
    }
    return 0;
}
 
 
/**************************************************************
    Problem: 1482
    User: cust123
    Language: C++
    Result: Accepted
    Time:30 ms
    Memory:1668 kb
****************************************************************/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值