首页 > 代码库 > POJ 3278 Catch That Cow
POJ 3278 Catch That Cow
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 43674 | Accepted: 13612 |
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
Output
Sample Input
5 17
Sample Output
4
Hint
Source
题目大意:
告诉你起点位置和终点位置,你可以有三种操作,从某个位置x,可以到达x-1,x+1,2*x,问你从起点到终点最短时间?
解题思路:
利用bfs枚举位置即可
但是刨除以下情况,也就是剪枝一下
1、当x<=0 时,x-1不能到达,这个状态剪掉
2、当x>终点位置时,x+1和2*x均不能到达
解题代码:
#include <iostream> #include <queue> using namespace std; const int maxn=210000; int marked,visited[maxn]; struct node{ int pos,t; node(int pos0=0,int t0=0){ pos=pos0;t=t0; } }; int main(){ int from,to; while(cin>>from>>to){ marked++; queue <node> q; q.push(node(from,0)); visited[from]=marked; while(!q.empty()){ node s=q.front(); q.pop(); if(s.pos==to){ cout<<s.t<<endl; break; } if( s.pos-1>=0 && visited[s.pos-1]!=marked){ visited[s.pos-1]=marked; q.push(node(s.pos-1,s.t+1)); } if( s.pos<=to && visited[s.pos+1]!=marked){ visited[s.pos+1]=marked; q.push(node(s.pos+1,s.t+1)); } if( s.pos<=to && visited[s.pos*2]!=marked){ visited[s.pos*2]=marked; q.push(node(s.pos*2,s.t+1)); } } } return 0; }