poj 3278 Catch That Cow

本文介绍了一个经典的抓牛问题,使用广度优先搜索(BFS)解决。问题设定为一个人从初始位置出发,通过前进、后退或当前位置翻倍的操作来抓住静止不动的牛,求最小步数。文章提供了完整的C++代码实现。

http://poj.org/problem?id=3278 题目输入n和m,n代表人的位置,m代表牛的位置,牛是不动的,而人动的规则是可以前进一步,后退一步,也可以直接在现在的位置上乘2(乘2算是一步),问你进过多少步可以最快的把牛抓到。

直接用bfs,调用库函数的队列就可以了

 1 #include<stdio.h>
2 #include<iostream>
3 #include<string.h>
4 #include<queue>
5 #define N 500000
6 using namespace std;
7 int move[2]={-1,1};
8 int mark[N];
9 int s,e;
10 struct node
11 {
12 int x,sum;
13 };
14
15 int bfs()
16 {
17 queue<node>qu;
18 int i;
19 node temp, k;
20 k.x=s;k.sum=0;
21 qu.push(k);
22 while(!qu.empty())
23 {
24 k=qu.front();qu.pop();
25 int flag=0;
26 for(i=0;i<3;i++)
27 {
28 if(i==2)
29 {
30 temp.x=2*k.x;
31 temp.sum=k.sum+1;
32 }
33 else
34 {
35 temp.x=move[i]+k.x;
36 temp.sum=k.sum+1;
37 }
38 if(temp.x==e)
39 {
40 flag=1;break;
41 }
42 if(temp.x<=e+1&&!mark[temp.x]&&temp.x<=500000&&temp.x>=0)
43 {
44 mark[temp.x]=1;
45 qu.push(temp);
46 }
47 }
48 if(flag) break;
49 }
50 return temp.sum;
51 }
52 int main()
53 {
54 while(cin>>s>>e)
55 {
56 mark[s]=1;
57 if(s>=e)
58 {
59 cout<<s-e<<endl;
60 continue;
61 }
62 memset(mark,0,sizeof(mark));
63 int ans=bfs();
64 cout<<ans<<endl;
65 }
66 return 0;
67 }

 

转载于:https://www.cnblogs.com/fxh19911107/archive/2012/03/05/2380902.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值