裸BFS题若干

1poj 3278

http://poj.org/problem?id=3278

#include<math.h>
#include<algorithm>
#include<string>
#include<string.h>
#include<stdio.h>
#include<iostream>

using namespace std;
#define N 100005
#define M 155
#define INF 0x3f3f3f3f
struct node
{
    int x, t;
}st;
int n, k, a, b, x, y, t, cnt, ans;
bool v[N];

void Bfs(int n)
{
    ans = 0;
    queue<node>q;
    while(!q.empty()) q.pop();
    memset(v, 0, sizeof(v));
    st.x = n;
    st.t = 0;
    q.push(st);
    v[st.x] = 1;

    while(!q.empty())
    {
        node head = q.front();
        q.pop();
        if(head.x == k)
        {
            ans = head.t;
            return;
        }

        for(int i = 0; i < 3; i++)
        {
            node next = head;
            if(i == 0) next.x = head.x + 1;
            else if(i == 1) next.x = head.x - 1;
            else next.x = head.x * 2;

            next.t = head.t + 1;

            if(next.x < 0 || next.x > 100000) continue;
            if(v[next.x] == 1 ) continue;
            // 一开始写成一行,if(v[next.x] == 1 || next.x < 0 || next.x > 100000) continue; 找了好久的bug,以后能分开的还是分开吧,不要省那一两行
            q.push(next);
            v[next.x] = 1;
        }
    }
}

int main()
{
    while(cin>>n>>k){

        Bfs(n);

        cout<<ans<<endl;

    }
    return 0;
}
原文地址:https://www.cnblogs.com/wmxl/p/11107303.html