Problem 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
Hint
The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.
【题目大意】:
一个农夫在数轴上抓奶牛的故事。农夫从n点出发,奶牛在k点且不会动。农夫每次向前一动一个单位或向后移动一个单位都会用掉一分钟,农夫还可以从x点瞬间转移到2 * x点,也只会消耗一分钟。问,农夫抓到奶牛的最短用时。
思路:本题n和k都是100000数量级,如果用dfs搜那就是个无底洞,时间复杂度O(3 ^ n)显然不行,那么就用广搜。
广搜思路也很直观,每次就三种状态的变化,所以可以写代码了:
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
const int maxn = 100005;
int n, k;
int tag[maxn];
struct Node{
int x;
int step;
Node(int x, int step)
{
this->x = x;
this->step = step;
}
};
bool panduan(int x)
{
if(x < 0 || x > 100000)
return false;
if(tag[x] == 1)
return false;
return true;
}
int bfs()
{
queue<Node> q;
q.push(Node(n, 0));
tag[n] = 1;
int res = 0;
while(!q.empty())
{
Node f = q.front();
if(f.x == k)
{
res = f.step;
break;
}
if(panduan(f.x + 1))
{
tag[f.x + 1] = 1;
q.push(Node(f.x + 1, f.step + 1));
}
if(panduan(f.x - 1))
{
tag[f.x - 1] = 1;
q.push(Node(f.x - 1, f.step + 1));
}
if(panduan(f.x * 2))
{
tag[f.x * 2] = 1;
q.push(Node(f.x * 2, f.step + 1));
}
q.pop();
}
return res;
}
int main()
{
while(cin >> n >> k) //此处如果用scanf("%d%d", &n, &k) != EOF就WA!
{
memset(tag, 0, sizeof(tag));
if(n >= k)
cout << n - k << endl;
else
cout << bfs() << endl;
}
return 0;
}
值得注意的就是第64行,输入的时候,如果用如果用scanf("%d%d", &n, &k) != EOF就会答案错误!hdu的评测系统有时候真的是很坑啊。。。又试了我半天,贡献了不少WA。。。