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;
}