本文主要是介绍POJ 3278 Catch That Cow -----BFS,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 115640 | Accepted: 36125 |
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.
题解:这道题其实是一道很简单的bfs的水题,但是我做这道题的时候提交了很多次都超时了,后来才发现几个必须要注意的地方:1、必须标记计算过的数据。2、每计算下一个数据m时要注意取值范围0<m<100005。3、当n>=k的时候直接输出n-k即可避免超时。
#include"iostream"
#include"string.h"
using namespace std;
int n,k,ans;
typedef struct
{int n;int pre;
}SQ;
SQ qu[100005];
int box[100005];
int front,rear;
void bfs(int n)
{rear=front=-1;rear++;qu[rear].n=n;qu[rear].pre=-1;box[n]=1;int m;while(front!=rear){front++;for(int i=0;i<3;i++){switch(i){case 0:m=qu[front].n-1;break;case 1:m=qu[front].n+1;break;case 2:m=qu[front].n*2;break;}if(box[m]==0&&m>0&m<100005){rear++;qu[rear].pre=front;qu[rear].n=m;box[m]=1;if(m==k)return ;}}}
}
int main()
{cin>>n>>k;memset(box,0,sizeof(box));if(n>=k)cout<<n-k<<endl;else{bfs(n);int s=qu[rear].pre;ans=0;while(s!=-1){ans++;s=qu[s].pre;}cout<<ans<<endl;}return 0;}
这篇关于POJ 3278 Catch That Cow -----BFS的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!