POJ 3278 Catch That Cow (bfs)(两种方式)
来源:互联网 发布:杭州认知网络 编辑:程序博客网 时间:2024/06/05 09:45
2016 CCPC 东北赛落幕了,结果很不理想。痛定思痛,究其原因还是个人实力太弱,要完成计划还是不能太过依靠队友。努力练吧,从头开始,仔仔细细从头学过。下次,一个人参赛吧。
回到这题,求最短路径,裸的bfs模板。bfs特性是就是返回一个最短的路径。
两种方式,一种STL,一种队列模拟。
STL容器():
#include<iostream>#include<cstring>#include<cstdio>#include<queue>#include<map>#include<cmath>using namespace std;const int maxn = 100005;bool vis[maxn];int step[maxn];int n,k;int dir[2]={1,-1};bool judge(int x){ if(x>=0&&x<=100000&&!vis[x]) return 1; return 0;}int bfs(){ memset(vis,0,sizeof(vis)); vis[n]=1; queue<int>q; q.push(n); step[n]=0; while(!q.empty()) { int cur=q.front(); q.pop(); for(int i=0;i<3;i++) { if(i<2) { int nxt = cur+dir[i]; if(judge(nxt)) { q.push(nxt); step[nxt]=step[cur]+1; vis[nxt]=1; } if(nxt==k)return step[nxt]; } else { int nxt = cur*2; if(judge(nxt)) { q.push(nxt); step[nxt]=step[cur]+1; vis[nxt]=1; } if(nxt==k)return step[nxt]; } } } return -1;}int main(){ while(cin>>n>>k) cout<<bfs()<<endl;}
队列模型和queue在bfs的实现是等效的。
数组:
#include<iostream>#include<cstdio>#include<cstring>using namespace std;struct node{ int x,step;}q[100005];bool vis[100005];int dir[2]={1,-1};bool judge(int x){ if(x>=0&&x<=100000&&!vis[x])return 1; return 0;}int bfs(int n,int k){ memset(vis,0,sizeof(vis)); vis[n]=1; int front = 0,rear = 1; q[front].x=n; q[front].step=0; while(front<rear) { node now = q[front++]; for(int i=0;i<3;i++) { if(i<2) { node cur = now; cur.x = now.x+dir[i]; if(judge(cur.x)) { vis[cur.x]=1; q[rear].x=cur.x; q[rear++].step=cur.step+1; } } else { node cur = now; cur.x = now.x*2; if(judge(cur.x)) { vis[cur.x]=1; q[rear].x=cur.x; q[rear++].step=cur.step+1; } } if(now.x==k)return now.step; } }}int main(){ int n,k; while(cin>>n>>k) cout<<bfs(n,k)<<endl;}
道路且险且远,吾自以此为戒。
0 0
- 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 3278Catch 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)
- netty 二进制简单通信
- arduino 资料
- Algorithm_Linked List
- ubuntu下opera浏览器安装Flash插件
- 数学之美系列
- POJ 3278 Catch That Cow (bfs)(两种方式)
- Android中Toast的用法简介
- PAT 1013 数素数 为什么一直是19分
- 使用Spinner实现下拉列表
- 计算机网络之GBN协议
- Mysqldump原理
- Android实践之简易天气(一)
- Java之十三 Java多线程
- Jersey 示例(一)