BFS.

CODE:

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <queue>
using namespace std;

const int SIZE = 100010;
#define low_bound 0
#define high_bound 100010

int v[SIZE];
int n, k;

struct node
{
    int x, step;
};

int check(int x)
{
    if(x >= low_bound && x <= high_bound) return 1;
        return 0;
}

int bfs(int s, int e)
{
    queue<node> Q;
    node inout;
    in.x = s;
    v[s] = 1;
    in.step = 0;
    Q.push(in);
    while(!Q.empty())
    {
        out = Q.front();
        Q.pop();
        int x = out.x;
        if(x == e)
        {
            printf("%d\n"out.step);
            return 1;
        }
        if(check(x-1) && !v[x-1])
        {
            in.x = out.x -1;
            v[x-1] = 1;
            in.step = out.step+1;
            Q.push(in);
        }
        if(check(x+1) && !v[x+1])
        {
            in.x = out.x+1;
            v[x+1] = 1;
            in.step = out.step+1;
            Q.push(in);
        }
        if(check(2*x) && !v[2*x])
        {
            in.x = out.x*2;
            v[x*2] = 1;
            in.step = out.step+1;
            Q.push(in);
        }
    }
    return 0;
}


int main()
{
    while(~scanf("%d%d", &n, &k))
    {
        memset(v, 0sizeof(v));
        int ans = bfs(n, k);
    }
    return 0;
}

 

 

 

posted on 2012-09-02 12:04  有间博客  阅读(155)  评论(0编辑  收藏  举报