#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
struct node
{
char num[4];
int step,hash;
void get_hash()
{
hash=(num[0]-'0')*1000+(num[1]-'0')*100+(num[2]-'0')*10+(num[3]-'0');
}
}f,temp;
int dp[2][10000];
void bfs()
{
queue<node>q[2];
int nowq=0,nowstep=0;
q[0].push(f);
q[1].push(temp);
dp[0][f.hash]=0;
dp[1][temp.hash]=0;
while(!q[0].empty()||!q[1].empty())
{
f=q[nowq].front();
if(f.step>nowstep)
{
nowq=!nowq;
nowstep++;
}
f=q[nowq].front();q[nowq].pop();
if(dp[!nowq][f.hash]!=-1)
{
printf("%d\n",f.step+dp[!nowq][f.hash]);
return;
}
int i,j;
for(i=0;i<4;i++)
{
for(j=0;j<3;j++)
{
temp=f;
temp.step++;
if(j==0)//第i位+
{
temp.num[i]++;
if(temp.num[i]>'9')temp.num[i]='1';
temp.get_hash();
}
else if(j==1)//第i位-
{
temp.num[i]--;
if(temp.num[i]<'1')temp.num[i]='9';
temp.get_hash();
}
else//交换第i位和它右边一位
{
if(i==3)continue;
swap(temp.num[i],temp.num[i+1]);
temp.get_hash();
}
if(dp[nowq][temp.hash]==-1)
{
dp[nowq][temp.hash]=temp.step;
q[nowq].push(temp);
}
}
}
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
memset(dp,-1,sizeof dp);
scanf("%s%s",f.num,temp.num);
f.get_hash();
f.step=0;
temp.get_hash();
temp.step=0;
bfs();
}
return 0;
}
HDU1195的双向bfs
最新推荐文章于 2025-08-14 18:10:12 发布