题目1482:玛雅人的密码

来源:互联网 发布:ubuntu 12.04 配置ip 编辑:程序博客网 时间:2024/04/27 23:03
#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****************************************************************/

0 0
原创粉丝点击