hdu 1195

// Accepted 1195 78MS 364K 2126 B C++ robotcator 
#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>

using namespace std;

const int maxn = 11000+50;
struct password{
  char data[5];
  int step;
};
password s, e;
int vis[maxn];

int get_key(password x){
  int sum = 0;
  for(int i = 0; i < 4; i ++)
    sum = sum*10 + x.data[i]-'0';
  return sum;
}

void bfs(){
  memset(vis, 0, sizeof(vis));
  queue<password> q;
  s.step = 0;
  q.push(s);
  vis[get_key(s)] = 1;
  password cur, next;
  while(!q.empty()){
      cur = q.front();
      q.pop();
      if(strcmp(cur.data, e.data) == 0){
        printf("%d\n", cur.step);
        return ;
      }
      for(int i = 0; i < 3; i ++){
          if(i == 0){ // 任意位上加1
            for(int j = 0; j < 4; j ++){
              strcpy(next.data, cur.data);
              next.data[j] = (next.data[j]-'0'+1) == 10 ? 1+'0' : next.data[j]+1;
              // 复制粘贴一定要注意代码间的区别
              if(vis[get_key(next)] == 0) {
                next.step = cur.step + 1;
                q.push(next);
                vis[get_key(next)] = 1;
                // 要区分等号和赋值号
              }
            }
          }
          else if(i == 1){ // 任意位上减1
            for(int j = 0; j < 4; j ++){
              strcpy(next.data, cur.data);
              next.data[j] = (next.data[j]-'0'-1) == 0 ? 9+'0' : next.data[j]-1;
              if(vis[get_key(next)] == 0) {
                next.step = cur.step + 1;
                q.push(next);
                vis[get_key(next)] = 1;
              }
            }
          }
          else if(i == 2){ // 交换
            for(int j = 0; j < 3; j ++){
              strcpy(next.data, cur.data);
              next.data[j] = cur.data[j+1];
              next.data[j+1] = cur.data[j];
              if(vis[get_key(next)] == 0) {
                next.step = cur.step + 1;
                q.push(next);
                vis[get_key(next)] = 1;
              }
            }
          }
      }
  }
}


int main()
{
  int t;
  scanf("%d", &t);
  while(t--){
    scanf("%s %s", s.data, e.data);
    bfs();
  }
  return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值