// 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;
}
hdu 1195
最新推荐文章于 2022-12-07 14:44:37 发布