http://acm.hdu.edu.cn/showproblem.php?pid=1195
题意:每一位上的数字可以加1或减1;相邻的数可以交换(第1个和第4个不相邻),变换得到下面的密码。
分析:两个评价函数:f=g+h(g:每一位上与答案不相同数字的个数;h:步数)
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
char strx[4],stry[4];
int vis[10005]; //判重
struct NUM{
char cs[4];
int pri,step;
evaluate(){
pri=0;
for(int i=0;i<4;i++){
if(cs[i]!=stry[i]) pri++;
}
}
};
bool operator < (struct NUM A,struct NUM B){
return A.pri>B.pri;
}
inline int convert(char *str)
{
int temp=0;
for(int i=0;i<4;i++){
temp=temp*10+(str[i]-'0');
}
return temp;
}
void BFS()
{
priority_queue<NUM>pq1;
NUM t,pt;
int i,temp;
char c1,c2;
memset(vis,0,sizeof(vis));
strcpy(t.cs,strx);
t.step=0;
temp=convert(t.cs);
vis[temp]=1;
pq1.push(t);
while(!pq1.empty()){
t=pq1.top();pq1.pop();
t.evaluate();
if(t.pri==0){
printf("%d\n",t.step);break;
}
pt.step=t.step+1;
for(i=0;i<4;i++){
strcpy(pt.cs,t.cs);
c1=c2=pt.cs[i]-'0';
c1++;
if(c1>9) c1=1;
pt.cs[i]=c1+'0';
temp=convert(pt.cs);
if(!vis[temp]){
vis[temp]=1;
pt.evaluate();pt.pri+=pt.step;
pq1.push(pt);
}
strcpy(pt.cs,t.cs);
c2--;
if(c2<1) c2=9;
pt.cs[i]=c2+'0';
temp=convert(pt.cs);
if(!vis[temp]){
vis[temp]=1;
pt.evaluate();pt.pri+=pt.step;
pq1.push(pt);
}
}
for(i=0;i<3;i++){
strcpy(pt.cs,t.cs);
c1=pt.cs[i];pt.cs[i]=pt.cs[i+1];pt.cs[i+1]=c1; //swap
temp=convert(pt.cs);
if(!vis[temp]){
vis[temp]=1;
pt.evaluate();pt.pri+=pt.step;
pq1.push(pt);
}
}
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--){
scanf("%s%s",strx,stry);
BFS();
}
return 0;
}