玛雅人的密码 广搜

裸的广搜,visited数组可以用一个map代替

#include <iostream>
#include <string>
#include <string.h>
#include <stdio.h>
#include <malloc.h>
#include <math.h>
#include <map>
#include <queue>
#define IN 1<<28
#define pi acos(-1.0)
using namespace std;
string str;
map<string,int> MyMap;
struct node
{
    int step;
    string data;
    node( int ss = 0, string dd = "\n" ):step(ss), data(dd){}
};
queue<node> MyQueue;
int N;
bool judge( string a )
{
    for( int i = 0; i < a.size()-3; i++ )
    {
        if( a.substr(i,4) == "2012" )
            return true;
    }
    return false;
}
string sww(string a, int i, int j )
{
    string res = a;
    char temp = a[i];
    res[i] = a[j];
    res[j] = temp;
    return res;
}
int main()
{
    while( cin >> N )
    {
      cin >> str;
      int flag = 0;
      while( !MyQueue.empty() )
        MyQueue.pop();
      MyQueue.push(node(0,str));
      while( !MyMap.empty() )
        MyMap.clear();
      while( !MyQueue.empty() )
      {
          node now = MyQueue.front();
          MyQueue.pop();
          if( judge(now.data) )
          {
              printf("%d\n", now.step);
              flag = 1;
              break;
          }
          for( int i = 0; i < N-1; i++ )
          {
              string temp = sww(now.data,i,i+1);
              if( MyMap[temp] != 1 )
              {
                  MyMap[temp] = 1;
                  MyQueue.push( node(now.step+1,temp) );
              }
          }
      }
      if( !flag )
      {
          printf("-1\n");
      }
    }
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值