There are three ways to move from point N to point M: * 2, + 1,-1. Calculates the minimum number of arriving steps.
Policy: for example, question.
Wa several times...
Only one set of data is input. It is best to put the queue declaration out of the function when using the queue. Otherwise, it is possible to submit the data with G ++ (user experience ). But it can be used in C ++.
Code 1 (the queue declaration is placed outside the function and can be a with C ++ and G ++ ):
# Include <stdio. h> # include <string. h ># include <queue> using namespace STD; int n, m, ans; bool vis [100005]; struct node {int cur, step;} st; queue <node> q; // is placed outside the function. Int BFS (INT cur) {St. cur = cur; ST. step = 0; q. push (ST); vis [st. cur] = 1; int I, j; while (! Q. empty () {node v = Q. front (); If (v. cur = m) {return v. step;} for (I = 0; I <3; I ++) {node u; if (I = 0) {u. cur = v. cur * 2; U. step = v. step + 1;} if (I = 1) {u. cur = v. cur + 1; U. step = v. step + 1;} if (I = 2) {u. cur = v. cur-1; U. step = v. step + 1;} If (U. cur> 100001 | u. cur <0) continue; If (U. cur = m) {return U. step;} If (! Vis [U. cur]) {vis [U. cur] = 1; q. push (u) ;}} Q. pop () ;}} int main () {scanf ("% d", & N, & M); ans = BFS (N ); printf ("% d \ n", ANS );}Code 2 (put in the function, C ++ can pass, but G ++ Wa is not clear ...)
# Include <stdio. h> # include <string. h ># include <queue> using namespace STD; int n, m, ans; bool vis [100005]; struct node {int cur, step;} st; int BFS (INT cur) {queue <node> q; // put it in St. cur = cur; ST. step = 0; q. push (ST); vis [st. cur] = 1; int I, j; while (! Q. empty () {node v = Q. front (); If (v. cur = m) {return v. step;} for (I = 0; I <3; I ++) {node u; if (I = 0) {u. cur = v. cur * 2; U. step = v. step + 1;} if (I = 1) {u. cur = v. cur + 1; U. step = v. step + 1;} if (I = 2) {u. cur = v. cur-1; U. step = v. step + 1;} If (U. cur> 100001 | u. cur <0) continue; If (U. cur = m) {return U. step;} If (! Vis [U. cur]) {vis [U. cur] = 1; q. push (u) ;}} Q. pop () ;}} int main () {scanf ("% d", & N, & M); ans = BFS (N ); printf ("% d \ n", ANS );}
Question link: Click the open link