您的位置:首页 > 其它

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遍历即可,搜索到的第一个解离根最近,一定是最优点。

代码:

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: