POJ 3278 Catch That Cow
来源:互联网 发布:php用apache还是nginx 编辑:程序博客网 时间:2024/06/07 06:56
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
题意:
给出起始位置n,有三种操作x+1,x-1,2*x,求最少的操作次数,使x==k。
题解:
广搜,裸的广搜会MLE,要加剪枝,还要用数组标记。一直MLE,就调整为每次出现一个新位置就判断是否结束,导致后来忘记考虑n==k的情况%>_<%
剪枝1.x>k,2*x不用走,只会越走越远。
剪枝2.x>k,x+1不用走,使x变小的只有x-1,x+1再x-1只会增加步数。
剪枝3.x-1>=0,x为负数时,只会增加步数或越走越远。
代码:
#include <iostream>#include <cstdio>#include <cstring>#include <queue>#include <algorithm>using namespace std;int n,k;int ans;const int maxn=200000+100;struct node{ int x; int cur;} p;bool vis[maxn];queue<node> q;void BFS(){ node p; p.x=n; p.cur=0; vis[n]=true; while(!q.empty()) q.pop(); q.push(p); while(!q.empty()) { node now; node tmp=q.front(); q.pop(); if(tmp.x==k)//n==k时 { ans=tmp.cur; return; } if(tmp.x<k&&!vis[tmp.x*2])//剪枝 { now.x=tmp.x*2; now.cur=tmp.cur+1; vis[now.x]=true; if(now.x==k) { ans=now.cur; return; } q.push(now); } if(tmp.x<k&&!vis[tmp.x+1])//剪枝 { now.x=tmp.x+1; now.cur=tmp.cur+1; vis[now.x]=true; if(now.x==k) { ans=now.cur; return; } q.push(now); } if(tmp.x-1>=0&&!vis[tmp.x-1])//剪枝 { now.x=tmp.x-1; now.cur=tmp.cur+1; vis[now.x]=true; if(now.x==k) { ans=now.cur; return; } q.push(now); } }}int main(){ while(~scanf("%d%d",&n,&k)) { memset(vis,false,sizeof(vis)); BFS(); printf("%d\n",ans); } return 0;}
- poj 3278 Catch That Cow
- POJ 3278 Catch That Cow
- poj 3278 catch that cow
- poj 3278 Catch That Cow
- POJ 3278 Catch That Cow
- Poj 3278 Catch That Cow
- POJ 3278 Catch That Cow
- POJ 3278 Catch That Cow
- POJ 3278 Catch That Cow
- poj 3278 Catch That Cow
- POJ 3278 Catch That Cow
- poj 3278 Catch That Cow
- poj 3278 Catch That Cow
- POJ 3278 Catch That Cow
- POJ 3278 - Catch That Cow
- POJ 3278 Catch That Cow
- POJ 3278 Catch That Cow
- POJ-3278-Catch That Cow
- TCP/IP 学习 (一)
- 《算法导论》笔记(10)贪心算法 部分习题
- SpringMVC数据格式化
- 基于核化相关滤波器的跟踪-效果直逼Struck和TLD跟踪器
- 简单的aes加密
- POJ 3278 Catch That Cow
- 浏览器停止支持SHA-1算法,我国用户如何应对?
- 数据库语言划分
- 机房重构中遇到的问题
- 《算法导论》笔记(11) 摊还分析 部分习题
- hdu 5126 stars cdq分治
- ViewPager实现TabHost动态添加、删除Fragment,用红色小圆球指示当前页面
- JDBC : Java获取数据库连接(Driver And DriverManager)
- NuGet 的基本语法