果然我还是不懂搜索,这道简单的,应该算得上是入门的级别的搜索我写代码+debug 花了我整整半天的时间,不过值得欣慰的是,我似乎悟懂了一点点“从当前状态搜索到其他状态”的方法和技巧。
【题面】
Catch That Cow
Description
Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.
- Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute
- Teleporting: FJ can move from any point X to the point 2 × X in a single minute.
If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?
Input
Line 1: Two space-separated integers: N and K
Output
Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
Sample Input
5 17
Sample Output
4
【题目大题】John 站在一根数轴上,他的牛也在这根数轴上,John 站在数轴上的某一点(设为x),每一次,他可以移动到当前这个点的左边一点(即x-1),或者当前这个点的右边一点(即x+1),或者穿越到数字为当前这个点的两倍的位置(即2*x),同时他的牛一直待在数轴中初始给的那个点不会移动到别的点。问John 最少移动几步可以抓到他的牛。
【解法】这是一道简单的bfs,当前点为x,有3个搜索方向,分别是x-1,x+1,2*x。
【技巧】
1:3个搜索方向,也就是3种数字变化规则,可以用3个函数,分别对应这3个数字变化规则, 然后将这3个函数放在函数指针数组中
2:先设ans=-1,一旦找到问题的解就把解存放在ans中。循环体while(!Q.empty()){……}的判断语句改变为while(!Q.empty() && ans != -1){……}
3:搜索的时候,队列中存放结构体,可以携带搜索树层数的信息。
【AC代码】
#include <cstring>
#include <cstdio>
#include <queue>
#define N 200005
using namespace std;
int Minus(int x){ ///减一
return x - 1;
}
int Add(int x){ ///加一
return x + 1;
}
int Multi(int x){ ///乘二
return 2 * x;
}
int (*ptr[3])(int x) = {Minus, Add, Multi}; ///函数指针数组
struct Point{
int num; ///数字
int depth; ///层数
};
int n, k;
int ans;
int vis[N];
bool check(int x){ ///判断写一个要进入的点x是不是合法的
if(vis[x] == 0 && x >= 0 && x <= 100000){
return true;
}
return false;
}
queue<Point>Q;
void bfs(int n, int depth){ ///bfs(n, depth)表示的是搜索位于第depth层的数字n
Point start; ///搜索起点
start.num = n;
start.depth = depth;
vis[n] = 1; ///起点标记为访问过
Q.push(start); ///起点入队
while(!Q.empty() && ans == -1){ ///ans == -1 这个条件很重要
Point temp = Q.front(); ///取出当前队首元素
Q.pop(); ///弹出队首元素
for(int i = 0; i < 3; i++){ ///检索3个方向
int cnt = (*ptr[i])(temp.num);
if(cnt == k){ ///找到答案
ans = temp.depth + 1;
}
else{
if(check(cnt)){ ///数字cnt合法
Point now;
now.num = cnt;
now.depth = temp.depth + 1;
vis[cnt] = 1; ///设置访问标记
Q.push(now); ///新的点入队
}
}
}
}
}
int main(){
while(scanf("%d%d", &n, &k) != EOF){
memset(vis, 0, sizeof(vis)); ///初始化部分
ans = -1; ///初始化部分
if(n == k){ ///起点即答案可直接输出
printf("0\n");
}
else{
bfs(n, 0); ///从位于第0层的点n开始搜索
printf("%d\n", ans);
}
while(!Q.empty()){ ///清空队列以备下次询问
Q.pop();
}
}
return 0;
}