题目:
Catch That Cow
Time Limit:2000MS Memory Limit:65536KB 64bit IO Format:%lld & %llu
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.
题意:
在0到100000这个闭区间长度内有一个人和一只牛,人有3种操作,一种是向左走一步,第二种是向右走一步,第三种是瞬移到当前位置的两倍,即从x瞬移到2*x,每种操作花费一分钟,问这个人最少需要多少时间到达牛的位置。
思路:
很简单,模拟人的3种操作进行bfs就可以了。
总结:
人生第一题bfs,难免会有错误。。。教训是,在此题中,已经进了队列的点,就不应该再进队列一次,试想一下每个进了队列的点,都按这个点进行了3次操作,意思是从这个点出发能到达的所有的点都已经入队,并且进行条件判断了,重复的入队,只会导致队列过长而MLE和TLE。
代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
struct node
{
int tag, time;
};
int vis[100000+10];
void bfs(int n, int k){
queue<node> q;
q.push(node{n, 0});
vis[n] = true;
while(!q.empty()){
node tmp = q.front(); q.pop();
if(tmp.tag==k) {cout<<tmp.time<<endl; return;}
if(tmp.tag-1>=0 && vis[tmp.tag-1]>tmp.time+1){
q.push(node{tmp.tag-1, tmp.time+1});
vis[tmp.tag-1] = tmp.time+1;
}
if(tmp.tag+1<=100000 && vis[tmp.tag+1]>tmp.time+1){
q.push(node{tmp.tag+1, tmp.time+1});
vis[tmp.tag+1] = tmp.time+1;
}
if(tmp.tag*2<=100000 && vis[tmp.tag*2]>tmp.time+1){
q.push(node{tmp.tag*2, tmp.time+1});
vis[tmp.tag*2] = tmp.time+1;
}
}
}
int main(){
int n, k;
while(cin>>n>>k){
memset(vis, 0x3f, sizeof(vis));
bfs(n, k);
}
return 0;
}
//重写了一次-2017-3-7..
//g++和c++选项...
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
struct node
{
int x, cost;
node(int x, int cost):x(x), cost(cost){}
};
const int MAXN = 100000;
bool vis[MAXN+5];
inline bool check(int x){
return (0<=x && x<=MAXN);
}
int bfs(int n, int k){
node t(n, 0);
queue<node> q;
q.push(t);
vis[t.x] = true;
memset(vis, 0, sizeof(vis));
while(!q.empty()){
t = q.front(); q.pop();
if(t.x==k) return t.cost;
if(check(t.x+1) && !vis[t.x+1]){
q.push(node(t.x+1, t.cost+1));
vis[t.x+1] = true;
}
if(check(t.x-1) && !vis[t.x-1]){
q.push(node(t.x-1, t.cost+1));
vis[t.x-1] = true;
}
if(check(t.x*2) && !vis[t.x*2]){
q.push(node(t.x*2, t.cost+1));
vis[t.x*2] = true;
}
}
}
int main(){
int n, k;
cin>>n>>k;
cout<<bfs(n, k)<<endl;
return 0;
}