玛雅人的密码 广搜

裸的广搜,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;
}

阅读更多
个人分类: 广度优先搜索
上一篇最小邮票数
下一篇动态规划 最大子序列和
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭