poj 3278 Catch That Cow(BFS)
来源:互联网 发布:免费手机图文编辑软件 编辑:程序博客网 时间:2024/06/06 08:38
*题意:
相当于在一个数轴上给定农夫的位置n与牛的位置k。假定牛不懂,农夫每次有三种移动方式:n+1.n-1.n*2。问农夫最少移动几步后才能到牛的位置。
*思路:
用bfs寻找最短路径。
*代码:
#include<iostream>#include<cstdio>#include<cstring>int queue[100001];bool visit[100001];int step[100001];using namespace std;void bfs(int n,int k){ memset(visit,0,sizeof(visit)); memset(step,0,sizeof(step)); int i,next,temp,flag=0; int front=0,back=1; visit[n]=1,queue[0]=n; step[n]=0; while(front<back) { temp=queue[front++]; for(i=0;i<3;i++) { if(i==0)next=temp+1; else if(i==1)next=temp-1; else next=temp*2; if(next<=100000&&next>=0&&!visit[next])//保证数组不越界,注意判断顺序,若!visit[next]在前会越界。 { visit[next]=1; queue[back++]=next; step[next]=step[temp]+1; } if(next==k) { flag=1; break; } } if(flag) break; } cout<<step[k]<<endl;}int main(){ int n,k; cin>>n>>k; if(n>=k) cout<<n-k<<endl; else bfs(n,k); return 0;}
注:1、这道题是第一次看bfs,看过之后感觉虽然题很简单但是对理解bfs的运行过程还是比较有帮助的。
2、做这道提示注意不要让数组越界,所以有判断语句并且要注意次序(就是因为这个re了好多次)。
- poj 3278 Catch That Cow(BFS)
- poj 3278 Catch That Cow BFS
- poj 3278 Catch That Cow BFS
- POJ 3278 Catch That Cow BFS
- poj 3278 bfs(Catch That Cow)
- poj 3278 Catch That Cow(bfs)
- POJ 3278 Catch That Cow bfs
- POJ 3278 Catch That Cow 【bfs+队列】
- POJ 3278 Catch That Cow (BFS)
- POJ 3278 Catch That Cow(BFS)
- poj 3278 Catch That Cow bfs
- poj 3278 Catch That Cow (BFS剪枝)
- POJ 3278 Catch That Cow[BFS]
- Poj 3278 Catch That Cow 裸bfs
- POJ 3278 Catch That Cow(图论:BFS)
- POJ 3278 Catch That Cow (BFS)
- POJ 3278 Catch That Cow (BFS)
- poj 3278 Catch That Cow 【BFS】
- sysfs详解
- string学习
- 偏序
- onvif开发总结
- 远程访问linux上 的mysql报 error 2003 : connection to mysql server on 10065
- poj 3278 Catch That Cow(BFS)
- RTTI运行时类型识别typeid,type_info,dynamic_cast关建字
- 能不能不这样搞,救援电话没有区号
- 11个重要的数据库设计规则
- python手记(28)
- Hibernate原生SQL查询
- maven build
- 大数据处理技术 - 基于Hadoop的实战
- Oracle instr函数