POJ 3278 Catch That Cow (BFS)


/*题意很简单,就是给你n和k,你需要计算从n到k最少需要多少步。
 n只能进行如下操作:1、走到n-1处  2、走到n+1处   3、走到2 * n处

 简单的BFS,需要注意的是如果n

 #include
 #include
 #include
 #define M 100000 + 10

 using namespace std;

 int n, k, sum;
 bool vis[M];
 struct node{
     int x;
     int step;
 }s, temp;

 void bfs()
 {
     s.x = n;
     s.step = 0;
     queueq;
     q.push(s);
     while(!q.empty())
     {
         s = q.front();
         q.pop();
         if(s.x == k)
         {
             cout<return ;
         }
         temp.x = s.x - 1;
         temp.step = s.step + 1;
         if(temp.x > 0 && !vis[temp.x])
         {
             vis[temp.x] = true;
             q.push(temp);
         }
         temp.x = s.x + 1;
         temp.step = s.step + 1;
         if(temp.x < M && !vis[temp.x])
         {
             vis[temp.x] = true;
             q.push(temp);
         }
         temp.x = s.x * 2;
         temp.step = s.step + 1;
         if(temp.x < M  && !vis[temp.x])
         {
             vis[temp.x] = true;
             q.push(temp);
         }
     }

 }

 int main()
 {
     while(cin>>n>>k)
     {
         if(n >= k)//易错点,如果不判断n,k大小,若n超级大则会错误
         {
              cout<continue;
         }

         sum = 0;
         memset(vis, false, sizeof(vis));
         vis[n] = true;
         bfs();
     }

     return 0;
 }

你可能感兴趣的:(POJ 3278 Catch That Cow (BFS))