Open the lock
Time Limit: 2000/1000 MS (Java/others) memory limit: 65536/32768 K (Java/Others)
Total submission (s): 4253 accepted submission (s): 1858
Problem descriptionnow an emergent task for you is to open a password lock. The password is consisted of four digits. Each digit is numbered from 1 to 9.
Each time, you can add or minus 1 to any digit. when Add 1 to '9', the digit will change to be '1' and when minus 1 to '1', the digit will change to be '9 '. you can also exchange the digit with its neighbor. each action will take one step.
Now your task is to use minimal steps to open the lock.
Note: The leftmost digit is not the neighbor of the rightmost digit.
Inputthe input file begins with an integer T, indicating the number of test cases.
Each test case begins with a four digit N, indicating the initial state of the password lock. then followed a line with anotther four dight M, indicating the password which can open the lock. there is one blank line after each test case.
Outputfor each test case, print the minimal steps in one line.
Sample Input
21234214411119999
Sample output
24
Learn to copy and paste BFS + priority queue
#include"stdio.h"#include"string.h"#include"queue"#include"algorithm"using namespace std;struct node{ int x,step; friend bool operator<(node a,node b) { return a.step>b.step; }};int a,b,c,d;int mark[10000];int fun(int x,int d){ x+=d; if(x==10) x=1; if(x==0) x=9; return x;}int fun2(int a,int b,int c,int d){ return a*1000+b*100+c*10+d;}void inti(int x){ a=x/1000;b=(x/100)%10; c=(x/10)%10;d=x%10;}int bfs(int s,int t){ int x; priority_queue<node >q; node cur,next; cur.x=s; cur.step=0; q.push(cur); memset(mark,0,sizeof(mark)); mark[s]=1; while(!q.empty()) { cur=q.top(); q.pop(); if(cur.x==t) return cur.step; next.step=cur.step+1; inti(cur.x); next.x=x=fun2(fun(a,1),b,c,d); if(!mark[x]) { mark[x]=1; q.push(next); } next.x=x=fun2(fun(a,-1),b,c,d); if(!mark[x]) { mark[x]=1; q.push(next); } next.x=x=fun2(a,fun(b,1),c,d); if(!mark[x]) { mark[x]=1; q.push(next); } next.x=x=fun2(a,fun(b,-1),c,d); if(!mark[x]) { mark[x]=1; q.push(next); } next.x=x=fun2(a,b,fun(c,1),d); if(!mark[x]) { mark[x]=1; q.push(next); } next.x=x=fun2(a,b,fun(c,-1),d); if(!mark[x]) { mark[x]=1; q.push(next); } next.x=x=fun2(a,b,c,fun(d,1)); if(!mark[x]) { mark[x]=1; q.push(next); } next.x=x=fun2(a,b,c,fun(d,-1)); if(!mark[x]) { mark[x]=1; q.push(next); } next.x=x=fun2(b,a,c,d); if(!mark[x]) { mark[x]=1; q.push(next); } next.x=x=fun2(a,c,b,d); if(!mark[x]) { mark[x]=1; q.push(next); } next.x=x=fun2(a,b,d,c); if(!mark[x]) { mark[x]=1; q.push(next); } } return 1;}int main(){ int T,s,t; scanf("%d",&T); while(T--) { scanf("%d%d",&s,&t); int ans=bfs(s,t); printf("%d\n",ans); } return 0;}