Catch That Cow
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
找奶牛可以说是经典广搜题了,这次没有用“正难则反”思想,是“堂堂正正”广搜。RE了7,8发
先上RE代码
#include<stdio.h>
#include<iostream>
#include<string>
#include<string.h>
#include<math.h>
#include<queue>
#define pii pair<int,int>
using namespace std;
const int N=100005;
bool vis[N];
int n,m;
int bfs(pii s){
queue<pii>q;
q.push(s);
vis[s.first]=1;
while(!q.empty()){
pii nowpos=q.front();q.pop();
if(nowpos.first==m)return nowpos.second;
if(nowpos.first>m&&!vis[nowpos.first-1]&&nowpos.first<N){
q.push(make_pair(nowpos.first-1,nowpos.second+1));
vis[nowpos.first-1]=1;
}
else if(nowpos.first>=0){
if(!vis[nowpos.first*2]&&2*nowpos.first<N&&nowpos.first)q.push(make_pair(nowpos.first*2,nowpos.second+1)),vis[nowpos.first*2]=1;
if(!vis[nowpos.first+1]&&nowpos.first+1<N)q.push(make_pair(nowpos.first+1,nowpos.second+1)),vis[nowpos.first+1]=1;
if(!vis[nowpos.first-1]&&nowpos.first-1>=0)q.push(make_pair(nowpos.first-1,nowpos.second+1)),vis[nowpos.first-1]=1;
}
}
return -1;
}
int main()
{
ios::sync_with_stdio(false);
while(cin>>n>>m){
memset(vis,0,sizeof(vis));
cout<<bfs(make_pair(n,0))<<endl;
}
return 0;
}
下面是Ac代码
#include<stdio.h>
#include<iostream>
#include<string>
#include<string.h>
#include<math.h>
#include<queue>
#define pii pair<int,int>
using namespace std;
const int N=100005;
bool vis[N];
int n,m;
int bfs(pii s){
queue<pii>q;
q.push(s);
vis[s.first]=1;
while(!q.empty()){
pii nowpos=q.front();q.pop();
if(nowpos.first==m)return nowpos.second;
if(nowpos.first<N&&nowpos.first>m&&!vis[nowpos.first-1]){
q.push(make_pair(nowpos.first-1,nowpos.second+1));
vis[nowpos.first-1]=1;
}
else if(nowpos.first>=0){
if(2*nowpos.first<N&&!vis[nowpos.first*2]&&nowpos.first)q.push(make_pair(nowpos.first*2,nowpos.second+1)),vis[nowpos.first*2]=1;
if(nowpos.first+1<N&&!vis[nowpos.first+1])q.push(make_pair(nowpos.first+1,nowpos.second+1)),vis[nowpos.first+1]=1;
if(nowpos.first-1>=0&&!vis[nowpos.first-1])q.push(make_pair(nowpos.first-1,nowpos.second+1)),vis[nowpos.first-1]=1;
}
}
return -1;
}
int main()
{
ios::sync_with_stdio(false);
while(cin>>n>>m){
memset(vis,0,sizeof(vis));
cout<<bfs(make_pair(n,0))<<endl;
}
return 0;
}
眼尖的小伙伴一定发现在查表时的数值
一定要先判边界