Catch That Cow POJ - 3278 (BFS)

题目链接: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[n] = true;
    if(n == m) ans = 0;
    else ans = solve(node(n, 0));
    printf("%d\n", ans);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值