Catch That Cow POJ - 3278 (BFS)
2017-08-14 17:23
429 查看
题目链接:https://vjudge.net/problem/POJ-3278
题目描述:给定起点n,终点k,设当前坐标为x,则每次可移动到x-1、x+1和2*x位置,均耗时一分钟。求起点到终点是否可达,若可达,求所需最小时间。
思路:bfs遍历即可,搜索到的第一个解离根最近,一定是最优点。
代码:
题目描述:给定起点n,终点k,设当前坐标为x,则每次可移动到x-1、x+1和2*x位置,均耗时一分钟。求起点到终点是否可达,若可达,求所需最小时间。
思路:bfs遍历即可,搜索到的第一个解离根最近,一定是最优点。
代码:
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> #include<queue> #include<cstdlib> #include<sstream> #include<deque> #include<stack> #include<set> #include<map> using namespace std; typedef long long ll; typedef unsigned long long ull; const double eps = 1e-6; const int maxn = 300001; const int mod = 10; const int dx[] = {1, -1, 0, 0}; const int dy[] = {0, 0, -1, 1}; const int Dis[] = {-1, 1, -5, 5}; const int inf = 0x3f3f3f3f; int n, m, k; bool vis[maxn]; struct node{ int point; int num; node(int point = 0, int num = 0) : point(point), num(num){} }; bool judge(int x){ return x >= 0 && x < maxn && !vis[x]; } int solve(node beg){ queue<node> que; que.push(beg); vis[beg.point] = true; while(!que.empty()){ node now = que.front(); que.pop(); if(now.point == m) return now.num; if(judge(now.point + 1)) vis[now.point + 1] = true, que.push(node(now.point + 1, now.num + 1)); if(judge(now.point - 1)) vis[now.point - 1] = true, que.push(node(now.point - 1, now.num + 1)); if(judge(now.point * 2)) vis[now.point * 2] = true, que.push(node(now.point * 2, now.num + 1)); } return -1; } int main(){ scanf("%d%d", &n, &m); int ans; memset(vis, false, sizeof vis); vis = true; if(n == m) ans = 0; else ans = solve(node(n, 0)); printf("%d\n", ans); return 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 3278 Catch That Cow(bfs实现)
- BFS-POJ-3278-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 && bzoj 1646: [Usaco2007 Open]Catch That Cow 抓住那只牛(BFS)
- POJ3278——Catch That Cow(BFS)