题目的意思是密码锁开锁的意思
用光搜写的:
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <string>
#include <queue>
using namespace std;
class NODE
{
public:
NODE(){};
NODE(const NODE &aa)
{
step=aa.step;
cur=aa.cur;
for(int i=1;i<=4;i++)
dig[i]=aa.dig[i];
};
NODE (int Step,int Cur,int tmp[])
{
step=Step;
cur=Cur;
for(int i=1;i<=4;i++)
dig[i]=tmp[i];
}
bool operator == (const NODE &a)
{
bool flag=true;
for(int i=1;i<=4;i++)
{
if(a.dig[i]!=dig[i])
{
flag=false;
break;
}
}
return flag;
};
int step;
int cur;
int dig[6];
};
int a[6],b[6];
bool vied_sum[10001];
void change(int left,int right,int a[])
{
a[left]=a[left]+a[right];
a[right]=a[left]-a[right];
a[left]=a[left]-a[right];
}
int Sum(int a[])
{
return (a[1]*1000+a[2]*100+a[3]*10+a[4]);
}
void bfs()
{
int cur=1;
queue<NODE>q;
q.push(NODE(0,0,a));
vied_sum[Sum(a)]=true;
NODE END(0,0,b);
while(!q.empty())
{
NODE tmp=q.front();
q.pop();
if(tmp==END)
{
cout<<tmp.step<<endl;
return ;
}
for(int i=1;i<=3;i++) //右交换
{
NODE tmp_right=tmp;
change(i,i+1,tmp_right.dig);
int sum=Sum(tmp_right.dig);
if(vied_sum[sum]==false)
{
tmp_right.step+=1;
q.push(tmp_right);
vied_sum[sum]=true;
}
}
for(int i=1;i<=4;i++) //直接减1
{
NODE tmp_down=tmp;
if(tmp_down.dig[i]==1)
tmp_down.dig[i]=9;
else
tmp_down.dig[i]=tmp_down.dig[i]-1;
int sum=Sum(tmp_down.dig);
if(vied_sum[sum]==false)
{
tmp_down.step+=1;
q.push(tmp_down);
vied_sum[sum]=true;
}
}
for(int i=2;i<=4;i++) //与左边的元素交换
{
NODE tmp_left=tmp;
change(i,i-1,tmp_left.dig);
int sum=Sum(tmp_left.dig);
if(vied_sum[sum]==false)
{
tmp_left.step+=1;
q.push(tmp_left);
vied_sum[sum]=true;
}
}
for(int i=1;i<=4;i++) //直接加1
{
NODE tmp_up=tmp;
if(tmp_up.dig[i]==9)
tmp_up.dig[i]=1;
else
tmp_up.dig[i]=tmp_up.dig[i]+1;
int sum=Sum(tmp_up.dig);
if(vied_sum[sum]==false)
{
tmp_up.step+=1;
q.push(tmp_up);
vied_sum[sum]=true;
}
}
}
while(!q.empty())
q.pop();
}
int main()
{
//freopen("in.txt","r",stdin);
int times;
cin>>times;
while(times--)
{
//memset(vied_per,false,sizeof(vied_per));
memset(vied_sum,false,sizeof(vied_sum));
string ss1,ss2;
cin>>ss1;
cin>>ss2;
for(int i=1;i<=4;i++)
a[i]=ss1[i-1]-'0';
for(int j=1;j<=4;j++)
b[j]=ss2[j-1]-'0';
bfs();
}
return 0;
}