HDU 2717 Catch That Cow
題目連結:傳送門
Problem 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
題目大意:給出兩個座標s,w。s在數軸上的行走規律是可以向左走一步,向右走一步,或跳到是當前座標位置的2倍的地方,而且這三種行走情況所消耗的時間都是一秒。求s到達w的最短時間。
#include<iostream> #include<cstring> #include<cstdio> #include<queue> using namespace std; int m[1000010]; int s,w; struct nm { int nat,tim; }; int bfs() { int a,b,c,d; nm next,tur; queue<nm>n; tur.nat=s; tur.tim=0; n.push(tur); m[s]=1; while(!n.empty()) { tur=n.front(); n.pop(); if(tur.nat==w) return tur.tim; if(m[tur.nat-1]==0&&(tur.nat-1)>=0&&(tur.nat-1)<=100010) { next.nat=tur.nat-1; next.tim=tur.tim+1; n.push(next); m[tur.nat-1]=1; } if(m[tur.nat+1]==0&&(tur.nat+1)>=0&&(tur.nat+1)<=100010) { next.nat=tur.nat+1; next.tim=tur.tim+1; n.push(next); m[tur.nat+1]=1; } if(m[tur.nat*2]==0&&(tur.nat*2)>=0&&(tur.nat*2)<=100010) { next.nat=tur.nat*2; next.tim=tur.tim+1; n.push(next); m[tur.nat*2]=1; } } return -1; } int main() { int a; while(cin>>s>>w) { memset(m,0,sizeof(m)); a=bfs(); cout<<a<<endl; } return 0; }