POJ3278Catch That Cow(线性模型)(BFS)
来源:互联网 发布:期货 期权 知乎 编辑:程序博客网 时间:2024/06/06 11:49
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
传送门
题意:实在鬼畜...John在0~100,000的某个位置上,牛也在某个位置上问,John通过题述的+1,-1,*2这几种变换方式能最少变换几次捉到牛。
求最少变换,用bfs,注意标记到达的数就不能再到达,否则会结束不了循环,而且有几个剪枝:
1.John不需要跑到负数的地方,因为跑到负数显然是由-1造成的,下一步只能+1,就等于走了两步废棋。
2.John不需要跑到100,000以外的地方,因为跑到100,000以外肯定是打算*2后再减去几次到达牛的位置。但是牛在100,000以内,*2后到达的位置一定是偶数,
所以离100,000最近的偶数是100002,所以还要减2步,所以一共走了3步,所以John从50,001的位置不需*2,直接-1,再*2也到达了100,000位置,所以又多走了一步废棋,若*2后不是100002,离100,000更远那么就多走了更多废棋。
//916K141MS#include<cstdio>#include<queue>#include<iostream>using namespace std;queue<pair<int,int> >que;//记录到达的位置和移动的步数int n,m;bool book[100100]; void bfs(){ que.push(make_pair(n,0)); book[n]=1; while(!que.empty()) { pair<int,int> t=que.front(); que.pop(); if(t.first==m) {printf("%d\n",t.second); break;} if(t.first+1<=100000&&!book[t.first+1]) {que.push(make_pair(t.first+1,t.second+1));book[t.first+1]=1;} if(t.first-1>=0&&!book[t.first-1]) {que.push(make_pair(t.first-1,t.second+1));book[t.first-1]=1;} if(t.first*2<=100000&&!book[t.first*2]) {que.push(make_pair(t.first*2,t.second+1));book[t.first*2]=1;} }}int main(){ scanf("%d%d",&n,&m); bfs(); return 0;}
- POJ3278Catch That Cow(线性模型)(BFS)
- poj3278Catch That Cow(bfs)
- POJ3278Catch That Cow(BFS)
- poj3278Catch That Cow(BFS)
- poj3278Catch That Cow bfs
- BFS POJ3278Catch That Cow
- poj3278Catch That Cow(bfs)
- POJ3278Catch That Cow(bfs)
- poj3278Catch That Cow
- poj3278Catch That Cow(AC)
- poj3278Catch That Cow
- poj3278Catch That Cow
- POJ3278Catch That Cow
- poj3278Catch That Cow 经典宽搜讲解
- Catch That Cow(BFS)
- hdoj2717Catch That Cow(BFS)
- Catch That Cow(BFS)
- Catch That Cow (BFS)
- 小P的故事——神奇的分组 背包
- Jquery 删除元素remove() detach() empty()比较
- lingo解决6个发点8个收点的最小运输费用问题
- 局域网聊天室
- HDU 1031 Design T-Shirt
- POJ3278Catch That Cow(线性模型)(BFS)
- 写给初学者的A*算法(A*Pathfinding for beginners)
- 用百度map api展示时空数据(一)
- IPSAN与FCSAN存储结构的区别
- 信号过系统问题
- PostgreSql的索引用法小结一
- Bluetooth 4.2 让每个蓝牙装置都有能连上网络的 IP 门牌,物联网应用更加到位
- Eclipse +Tomcat8.0配置Javaweb 开发环境
- HDU1251统计难题(字典树模板)