Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 68975 | Accepted: 21699 |
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
Output
Sample Input
5 17
Sample Output
4
Hint
题意:初始点在N,目标点在K,但是每分钟只能向前或后退一步,或者到达这个点的2倍的点。最快要多久能从N点到达K点。
思路: 每次有三种情况,随意就是用了BFS,刚写成的时候,没有优化,导致超内存,后来修改,如果当前点超过了目标点K,就不再向前走,如果当前点小于0,就不能在后退,之后又TLE,然后发现没有优化那些走过的点,再次修改,终于AC了
代码如下:
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#define MXAN 1000005
using namespace std;
struct Node
{
int add,step;//add代表当前地址,step代表步数
};
int N,K;
bool ok[MXAN]; //标记这点是否到达过
queue<Node> Q;
int bfs()
{
int r,c;
Node tem={N,0};
Q.push(tem);
while(!Q.empty())
{
tem=Q.front();
if(tem.add==K) break;
Q.pop();
if(!ok[tem.add]) //如果这点遍历过,就不能在遍历
{
if(tem.add<K ) //如果这点小于目标点,可以继续+1或*2
{
r=tem.add+1;
Node temp={r,tem.step+1};
Q.push(temp);
c=tem.add*2;
Node tep={c,tem.step+1};
Q.push(tep);
}
if(tem.add>0 && !ok[tem.add]) //如果这点大于0,就能向后走
{
r=tem.add-1;
Node tp={r,tem.step+1};
Q.push(tp);
}
ok[tem.add]=true; //把这点标记为已经遍历过
}
}
while(!Q.empty())
{
Q.pop();
}
return tem.step;
}
int main()
{
memset(ok,0,sizeof(ok));
scanf("%d%d",&N,&K);
int ans=bfs();
printf("%d\n",ans);
return 0;
}