点击打开链接
2 1234 2144 1111 9999
2 4
#include<stdio.h> #include<iostream> #include<string.h> #include<queue> using namespace std; typedef struct Node { char s[5]; int time; friend bool operator <(Node a,Node b) { return b.time<a.time; } }node; char aa[5],bb[5]; int Time,visit[10000]; void change(char *x,char *y) { char t; t=*x;*x=*y;*y=t; } void BFS() { priority_queue<node> que; node q,p; int i; char s1[5]; strcpy(q.s,aa);q.time=0; visit[(q.s[0]-'0')*1000+(q.s[1]-'0')*100+(q.s[2]-'0')*10+(q.s[3]-'0')]=1; que.push(q); while(!que.empty()) { q=que.top(); que.pop(); if(strcmp(q.s,bb)==0) { Time=q.time; return ; } p.time=q.time+1; for(i=0;i<3;i++) { strcpy(s1,q.s); change(&s1[i],&s1[i+1]); strcpy(p.s,s1); if(visit[(p.s[0]-'0')*1000+(p.s[1]-'0')*100+(p.s[2]-'0')*10+(p.s[3]-'0')]==0) { visit[(p.s[0]-'0')*1000+(p.s[1]-'0')*100+(p.s[2]-'0')*10+(p.s[3]-'0')]=1; que.push(p); } } for(i=0;i<4;i++) { strcpy(p.s,q.s); if(p.s[i]!='9') p.s[i]+=1; else p.s[i]='1'; if(visit[(p.s[0]-'0')*1000+(p.s[1]-'0')*100+(p.s[2]-'0')*10+(p.s[3]-'0')]==0) { visit[(p.s[0]-'0')*1000+(p.s[1]-'0')*100+(p.s[2]-'0')*10+(p.s[3]-'0')]=1; que.push(p); } } for(i=0;i<4;i++) { strcpy(p.s,q.s); if(p.s[i]!='1') p.s[i]-=1; else p.s[i]='9'; if(visit[(p.s[0]-'0')*1000+(p.s[1]-'0')*100+(p.s[2]-'0')*10+(p.s[3]-'0')]==0) { visit[(p.s[0]-'0')*1000+(p.s[1]-'0')*100+(p.s[2]-'0')*10+(p.s[3]-'0')]=1; que.push(p); } } } } int main() { int t,i; char ch; scanf("%d",&t); while(t--) { memset(visit,0,sizeof(visit)); scanf("%s%s",aa,bb); Time=0; BFS(); printf("%d\n",Time); } return 0; }