A BFS problem, dare not say water. Well, the question is really an introductory question ....
Because I did it for almost 2 hours.
Or because of the incomplete thinking consideration;
In the beginning, the addition and subtraction of the situation are written in a loop ... Hand it over, WA.
Check it out for a long time before you check it out .... The process of printing out there are not reliable places ...
Later analysis of the logic ... Found that the previous changes will affect the number of changes in the face of the post, in fact, I made 2 changes, only recorded once;
And it also reduces the pressure in the queue ...
Later when the change of the addition of a part of the less ... And it took a little time to debug.
But what do you say? Finally, I did it ...
1#include <iostream>2#include <queue>3#include <string.h>4#include <algorithm>5 using namespacestd;6 #defineMAXN 100057 structnode{8 intcount;9 inta[4];Ten }; One BOOLVISIT[MAXN]; A intN; - intBegin_value,end_value; - intGetValue (int*a) the { - intresult =0; - for(inti =0; I <4; i++){ -result = result *Ten+A[i]; + } - returnresult; + } A intBFS () at { -Queue<node>game; - node cur, next; -Cur.count =0; -cur.a[0] = Begin_value/ +; -cur.a[1] = (begin_value% +) / -; incur.a[2] = (begin_value% -) /Ten; -cur.a[3] = begin_value%Ten; to Game.push (cur); +Visit[getvalue (CUR.A)] =true; - while(!Game.empty ()) { theCur =Game.front (); * Game.pop (); $ intValue =GetValue (CUR.A);Panax Notoginseng //printf ("%d%d\n", value,cur.count); - if(Value = =end_value) { the returnCur.count; + } A //Subtraction: the for(inti =0; I <4; i++){ +Next =cur; - if(Cur.a[i] = =1){ $Next.a[i] =9; $ if(!Visit[getvalue (NEXT.A)]) - { -Next.count = Cur.count +1; theVisit[getvalue (next.a)] =true; - Game.push (next);Wuyi } the } - Else{ WuNext.a[i] = cur.a[i]-1; - if(!Visit[getvalue (NEXT.A)]) About { $Next.count = Cur.count +1; -Visit[getvalue (next.a)] =true; - Game.push (next); - } A + } the } - //addition $ for(inti =0; I <4; i++){ theNext =cur; the if(Cur.a[i] = =9){ theNext.a[i] =1; the if(!Visit[getvalue (NEXT.A)]) - { inNext.count = Cur.count +1; theVisit[getvalue (next.a)] =true; the Game.push (next); About } the } the Else{ theNext.a[i] = Cur.a[i] +1; + if(!Visit[getvalue (NEXT.A)]) - { theNext.count = Cur.count +1;BayiVisit[getvalue (next.a)] =true; the Game.push (next); the } - } - } the for(inti =0; I <3; i++) the { theNext =cur; theSwap (Next.a[i], next.a[i +1]); - if(!Visit[getvalue (NEXT.A)]) the { theNext.count = Cur.count +1; theVisit[getvalue (next.a)] =true;94 Game.push (next); the the } the }98 } About return 0; - }101 102 intMain ()103 {104 while(~SCANF ("%d", &N)) { the while(n--){106scanf"%d%d", &begin_value, &end_value);107memset (Visit,false,sizeof(visit));108printf"%d\n", BFS ());109 } the }111 return 0; the}
hdu1195 Open the Lock