POJ - 3278 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
目前只尝试了BFS,不会超时。
1 #include<iostream> 2 #include<queue> 3 using namespace std; 4 5 int line[200000]={0};//number line ,这里选择最大长度的2倍 6 int N,K; 7 queue<int> q; //BFS队列 8 9 int main(){ 10 cin >>N>>K; 11 if(N==K){ //这里是一个坑!要单独判断N==K的情况 12 cout <<0<<endl; 13 system("pause"); 14 return 0; 15 } 16 //BFS 17 q.push(N); 18 while(!q.empty()){ 19 int u=q.front(); 20 q.pop(); 21 int choice[3]; 22 choice[0]=u-1; //三种可能的移动目标位置 23 choice[1]=u+1; 24 choice[2]=2*u; 25 for(int i=0;i<3;i++){ 26 if(choice[i]>=0&&choice[i]<200000&&line[choice[i]]==0){ 27 line[choice[i]]=line[u]+1; 28 q.push(choice[i]); 29 if(choice[i]==K){ //如果到达K点就结束 30 cout <<line[choice[i]]<<endl; 31 break; 32 } 33 } 34 } 35 } 36 system("pause"); 37 return 0; 38 }
需要注意的一点就是边界情况要记得去考虑一下有没有包含进来,这里N==K这个情况没有考虑到的话就会WA


浙公网安备 33010602011771号