poj 3278 BFS

思路:
BFS。
BFS的目标就是求最短(可能是最短路径长度,可能是最短路径)。

本题就是通过BFS来求最短路径长度。

每次有三个方向来扩展状态(想象成三叉树)。


#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <algorithm>
#include <fstream>
#include <cmath>
#include <cstring>
#include <limits.h>

#define Long long long
#define uint unsigned int
#define N
#define mod 1000000007
#define inf 100005
#define eps 1e-10
#define For(i,l,r) for(int i=l;i<=r;i++)
#define Dor(i,r,l) for(int i=r;i>=l;i--)

using namespace std;

ifstream in("/Users/urey/data/input.txt");
//_________________________________________________________________________________

int gcd(int a, int b) {
    if(b == 0)
        return a;
    return gcd(b, a%b);
}

int n ,k;
queue<int> q;
int step[inf];
bool visit[inf];
int head;

int bfs() {
    q.push(n);
    step[n] = 0;
    visit[n] = 1;
    while(!q.empty()) {
        head = q.front();
        q.pop();
        if(head == k) {
            return step[head];
        }
        //方向一
        if(head * 2 < inf && !visit[head * 2]) {
            q.push(head*2);
            visit[head*2] = 1;
            step[head*2] = step[head] + 1;
        }
        //方向二
        if(head + 1 < inf && !visit[head + 1]) {
            q.push(head + 1);
            visit[head + 1] = 1;
            step[head + 1] = step[head] + 1;
        }
        //方向三
        if(head - 1 >= 0 && !visit[head - 1]) {
            q.push(head - 1);
            visit[head - 1] = 1;
            step[head - 1] = step[head] + 1;
        }
    }
    return -1;
}

int main(int argc, const char * argv[]) {
    cin>>n>>k;
    if(n >= k) {
        cout<<n-k<<endl;
    }else {
        cout<<bfs()<<endl;
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值