ime Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 119162 | Accepted: 37180 |
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
解题思路:
DFS,BFS都可以都可以,就这道题而言,深搜比较慢。
按层便利每个元素,找到牛的位子就输出深度。
#include<iostream>
#include<queue>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 100000;
bool visited[maxn+10];
struct step{
int x;
int steps;
step(int xx,int y):x(xx),steps(y) {}
};
int main()
{
int n,k;
scanf("%d%d",&n,&k);
queue<step> que;
que.push(step(n,0));
visited[n] = 1;
memset(visited,0,sizeof(visited));
while(!que.empty()){
step s = que.front();
if(s.x == k){
printf("%d",s.steps);
return 0;
}
else{
if(s.x - 1 >= 0 && !visited[s.x - 1]){
que.push(step(s.x-1,s.steps+1));
visited[s.x - 1] = 1;
}
if(s.x + 1 <= maxn && !visited[s.x + 1]){
que.push(step(s.x+1,s.steps+1));
visited[s.x + 1] = 1;
}
if(2*s.x <= maxn && !visited[2 * s.x]){
que.push(step(2*s.x,s.steps+1));
visited[2 * s.x] = 1;
}
}
que.pop();
}
return 0;
}