[POJ 3278] Catch That Cow

题目链接:http://poj.org/problem?id=3278

题目理解:

从当前点N,到点K,可以选择的方式有三种,分别是:当前位置+1,当前位置-1,当前位置×2;

求走的最少步数。

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<queue>
 4 #include<cstring>
 5 using namespace std;
 6 
 7 bool vis[200100];
 8 int n,k;
 9 struct node
10 {
11     int x,step;
12 };
13 
14 void bfs(int n,int k)
15 {
16     queue<node> Q;
17     node s,sx;
18     s.x = n;s.step = 0;
19     Q.push(s);
20     while(!Q.empty())
21     {
22         s = Q.front();
23         Q.pop();
24         if(s.x == k)
25         {
26             printf("%d
",s.step);
27             return ;
28         }
29         else
30         {
31             //用一个中间变量sx的原因是在三个if全部判断完之前不改变当前状态的变量的值;
32             if(s.x>0&&!vis[s.x-1])
33             {
34                 sx.x = s.x - 1;
35                 sx.step = s.step + 1;
36                 vis[s.x-1] = 1;
37                 Q.push(sx);
38             }
39             if(s.x<=k&&!vis[s.x+1])
40             {
41                 sx.x = s.x + 1;
42                 sx.step = s.step + 1;
43                 vis[s.x+1] = 1;
44                 Q.push(sx);
45             }
46             if(s.x<=k&&!vis[2*s.x])
47             {
48                 sx.x = 2 * s.x;
49                 sx.step = s.step + 1;
50                 vis[2*s.x] = 1;
51                 Q.push(sx);
52             }
53         }
54     }
55 }
56 
57 int main()
58 {
59     while(scanf("%d%d",&n,&k)!=EOF)
60     {
61         memset(vis,0,200100);
62         bfs(n,k);
63     }
64     return 0;
65 }
原文地址:https://www.cnblogs.com/youpeng/p/10223672.html