POJ3278,自己写了代码不知道哪里错,希望有人能解答!

wehan 2016-02-25 07:00:25
题目是这样的:
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.

我的代码:(C语言,勿喷)//还没学C++,不是特别懂<queue>


#include<stdio.h>
#include<cstdio>
int num[100001] = { 0 }, f[100001] = { 0 };
int main()
{
int n, k, index = 0, front=0,end=0;
scanf("%d%d", &n, &k);
num[end++] = n;
if (n == k)
{
printf("0\n");
return 0;
}
while (1)
{
n = num[front++];
if (n == k)
{
printf("%d\n", f[n]);
break;
}
index = f[n] + 1;
if (n != 0 && !f[n - 1])
{
num[end++] = n - 1;
f[n - 1] = index;
}
if (n + 1 <= k&&!f[n + 1])
{
num[end++] = n + 1;
f[n + 1] = index;
}
if (n * 2 <= k&&!f[n * 2])
{
num[end++] = n * 2;
f[n * 2] = index;
}
}
return 0;
}
...全文
208 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
wehan 2016-02-26
  • 打赏
  • 举报
回复
已经找到了错误点……在判断的时候不应该是n-1<k和n*2<k,而应该是小于100001
fly_dragon_fly 2016-02-26
  • 打赏
  • 举报
回复
使用bfs应该是习惯while(front!=end or front<end) 题目没说一定能找到,看定义num是队列,f是步长,感觉缺少判重, 这个点已经访问过没判断

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧