BFS POJ3278Catch That Cow

来源:互联网 发布:知已知彼的意思是什么 编辑:程序博客网 时间:2024/05/17 00:57

Catch That Cow
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 62866 Accepted: 19675
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.
Source
USACO 2007 Open Silver
用BFS,从起点开始,记录时间每增加一分钟能到达的所有点,到达这些点的时间就是相应的最短用时。
用归纳法证明:
假设当前点在点2处。那么到2-1,2+1,2*2处的时间是到点2的时间上加上一分钟,都是到各点最短的用时。
假设当前点在x(x大于等于2)处,并且走到x处的用时Time是到x处用时的最短时间。那么,到x-1,x+1,2x处的用时Time+1也是到相应处最短的用时。
归纳法可证,从起点开始,对每个点y,依次遍历y+1,y-1,y*2,分别能得到到y+1,y-1,y*2的最短用时。

#include <cstring>#include <queue>#include<iostream>#include<cstdio>#define INF 0x7fffffff#define MAXN 100005using namespace std;int startX,endX,vis[MAXN],_time[MAXN];void BFS(){    memset(vis,0,sizeof(vis));    queue<int> q;    q.push(startX);    vis[startX]=1;    _time[startX]=0;    int nowX;    while(!q.empty()&&!vis[endX]){        nowX=q.front();        q.pop();        if(nowX-1>=0&&!vis[nowX-1]){//注意临界条件            vis[nowX-1]=1;            _time[nowX-1]=_time[nowX]+1;            q.push(nowX-1);        }        if(nowX-1==endX) break;//到达即退出        if(nowX+1<MAXN&&!vis[nowX+1]){            vis[nowX+1]=1;            _time[nowX+1]=_time[nowX]+1;            q.push(nowX+1);        }        if(nowX+1==endX) break;        if(nowX*2<MAXN&&!vis[nowX*2]){            vis[nowX*2]=1;            _time[nowX*2]=_time[nowX]+1;            q.push(nowX*2);        }         if(nowX<<1==endX) break;    }    cout<<_time[endX]<<endl;}int main(){  freopen("input.txt","r",stdin);  freopen("output.txt","w",stdout);  while(scanf("%d%d",&startX,&endX)!=EOF){    BFS();  }  return 0;}
0 0
原创粉丝点击