poj3278 Catch That Cow

FJ要抓奶牛。
开始输入N(FJ的位置)K(奶牛的位置)。
FJ有三种移动方法:1、向前走一步,耗时一分钟。
2、向后走一步,耗时一分钟。
3、向前移动到当前位置的两倍N*2,耗时一分钟。
问FJ抓到奶牛的最少时间。奶牛不会动。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include<iostream>
#include<queue>
#include<cstring>
#include<cstdio>
using namespace std;
const int maxn=100001;
bool vis[maxn];
int step[maxn];
void bfs(int n,int k)
{
memset(step,0,sizeof(step));
memset(vis,false,sizeof(vis));
queue <int> q;
int p,tmp;
q.push(n);
step[n]=0;
vis[n]=true;
while(!q.empty()) {
p=q.front();
q.pop();
if(p==k){printf("%d\n",step[p]);return ;}
for(int i=0;i<3;i++) {
if(i==0) tmp=p-1;
else if(i==1) tmp=p+1;
else tmp=p*2;
if(tmp<0 || tmp>=maxn) continue;
if(!vis[tmp]) {
q.push(tmp);
step[tmp]=step[p]+1;
vis[tmp]=true;
}
}
}
}
int main()
{
int n,k;
while(scanf("%d%d",&n,&k)!=EOF){
if(n>=k) printf("%d\n",n-k);
else
bfs(n,k);
}
return 0;
}

-------------本文结束感谢您的阅读-------------
0%