POJ3278-Catch That Cow

大致题意:

给定两个整数n和k

通过 n+1或n-1 或n*2 这3种操作,使得n==k

输出最少的操作次数

解题思路:

三入口的BFS

注意的地方:

由于用于广搜的 队列数组 和 标记数组  相当大,如果定义这两个数组时把它们扔到局部去,编译是可以的,但肯定执行不了,提交就等RE吧= =

大数组必须开为 全局 。。。常识常识。。。

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 using namespace std;
 5 #include <queue>
 6 #define N 100005
 7 int n,k;
 8 bool mark[N];
 9 int main()
10 {
11     while (scanf("%d %d",&n,&k)!=EOF)
12     {
13         queue<int> q,a;
14         memset(mark,0,sizeof(mark));
15         q.push(n);
16         a.push(0);
17         mark[n]=1;
18         while (!q.empty())
19         {
20              int temp=q.front();
21              int ans=a.front();
22              q.pop();
23              a.pop();
24              if (temp==k)
25              {
26                  printf("%d\n",ans);
27                  break;
28              }
29              if (temp+1<=100000&&!mark[temp+1])
30              {
31                  q.push(temp+1);
32                  a.push(ans+1);
33                  mark[temp+1]=1;
34              }
35              if (temp-1>=0&&!mark[temp-1])//注意边界条件temp-1>=0
36              {
37                  q.push(temp-1);
38                  a.push(ans+1);
39                  mark[temp-1]=1;
40              }
41              if (temp*2<=100000&&!mark[temp*2])
42              {
43                  q.push(temp*2);
44                  a.push(ans+1);
45                  mark[temp*2]=1;
46              }
47         }
48     }
49 
50     return 0;
51 }

猜你喜欢

转载自www.cnblogs.com/hemeiwolong/p/9296493.html