C - Catch That Cow POJ - 3278
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.
脑海里的模型:一维的搜索
解法:跟二维的不同也是在于方向,是规定的三个,要么+1,要么-1,要么*2,BFS找出最短路径
遇到的阻碍就是第一次提交时Runtime erro,我开的数组是100005,没有考虑到要判断农夫 teleporting的时候会让标记数组超出边界,于是我加了个判断他不能走到小于0或者超过100000
第二次提交wa的原因是,当农夫和牛一开始就在同一个地方的时候没有判断
以下是BFS代码:
#include<iostream>
#include<queue>
using namespace std;
int N,K;
bool vis[300005];
struct node{
int x;
int step;
};
void bfs(){
queue<node>q;
node n;
n.step=0;
n.x=N;
q.push(n);
while(!q.empty()){
node tmp=q.front();
q.pop();
n.step=tmp.step+1;
vis[N]=1;
int t[3];
t[0]=tmp.x+1;
t[1]=tmp.x-1;
t[2]=tmp.x*2;
for(int i=0;i<3;i++){
if(vis[t[i]]!=1&&t[i]>=0&&t[i]<=100000){
if(t[i]==K){
cout<<n.step<<endl;
return ;
}
vis[t[i]]=1;
n.x=t[i];
q.push(n);
}
}
}
}
int main(){
cin>>N>>K;
if(N==K)
cout<<'0'<<endl;
else
bfs();
return 0;
}
To conclusion:广搜的题做多之后发现套路都差不多,要是想要统计层数的话,开全局变量我是行不通的,所以得要用一个结构体来存每一个点它被搜到时候的层数,然后下一层的时候再用队列pop出来的那个上一层的点的层数加一就好了
还有一点就是别忘了用标记数组。