题目网址: C - 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 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.题意:有个人要找他的牛,他跟他的牛在同一条线上,可以理解为是他们分别在在数轴上的某个位置,第一个数是他的位置,第二个数是他牛的位置,他每次可以前进一步或者后退一步,或者跳一下跳到当前位置乘2的位置;问最少需要多少步他能找到他的牛;
思路:直接BFS就过了;首先如果他的牛在他后边,他就只能通过后退到达,直接输出S-E就OK;否则每次加入三种状态(如果有状态可行):+1,-1,*2;步数加一;找到了就直接输出;
#include<iostream> #include<cstdio> #include<cmath> #include<cstring> #include<algorithm> #include<queue> using namespace std; int S,E,v[100001]; typedef struct node { int x,ans; }N; int bfs() { queue<N>q; N now;now.x=S;now.ans=0; q.push(now); while(!q.empty()) { now=q.front(); q.pop(); N next1,next2,next3; next1.x=now.x-1;next1.ans=now.ans+1; next2.x=now.x*2;next2.ans=now.ans+1; next3.x=now.x+1;next3.ans=now.ans+1; if(next1.x>0&&next1.x<100001&&v[next1.x]==false) { if(next1.x==E) { return next1.ans; } v[next1.x]=true; q.push(next1); } if(next2.x>0&&next2.x<100001&&v[next2.x]==false) { if(next2.x==E) { return next2.ans; } v[next2.x]=true; q.push(next2); } if(next3.x>0&&next3.x<100001&&v[next3.x]==false) { if(next3.x==E) { return next3.ans; } v[next3.x]=true; q.push(next3); } } return -1; } int main() { while(cin>>S>>E) { memset(v,false,sizeof(v)); if(S>=E) { cout<<S-E<<endl; } else { cout<<bfs()<<endl; } } return 0; }