码迷,mamicode.com
首页 > 其他好文 > 详细

poj3278(bfs)

时间:2014-12-16 18:49:17      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   ar   io   color   os   sp   on   

 

题目链接:http://poj.org/problem?id=3278

分析:广搜,每次三种情况枚举一下,太水不多说了。

 

bubuko.com,布布扣
#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <queue>
#include <cstdlib>
#include <vector>
#include <set>
#include <map>
#define LL long long
#define mod 1000000007
#define inf 0x3f3f3f3f
#define N 100010
using namespace std;
struct node
{
    int x,step;
    bool operator<(const node a)const
    {
        return step>a.step;
    }
};
priority_queue<node>que;
int vis[N];
int judge(int x)
{
    return x>=0&&x<=100000;
}
node make_node(int a,int b)
{
    node temp;
    temp.x=a;temp.step=b;
    return temp;
}
int main()
{
    int n,k;
    while(scanf("%d%d",&n,&k)>0)
    {
        memset(vis,0,sizeof(vis));
        while(!que.empty())que.pop();
        que.push(make_node(n,0));
        vis[n]=1;
        int ans=0;
        while(!que.empty())
        {
            node now=que.top();
            que.pop();
            int x=now.x;//printf("%d %d\n",now.x,now.step);
            if(x==k)
            {
                ans=now.step;
                break;
            }
            if(judge(x+1)&&!vis[x+1])
            {
                vis[x+1]=1;que.push(make_node(x+1,now.step+1));
            }
            if(judge(x-1)&&!vis[x-1])
            {
                vis[x-1]=1;que.push(make_node(x-1,now.step+1));
            }
            if(judge(2*x)&&!vis[x*2])
            {
                vis[x*2]=1;que.push(make_node(2*x,now.step+1));
            }
        }
        printf("%d\n",ans);
    }
}
View Code

 

poj3278(bfs)

标签:style   blog   http   ar   io   color   os   sp   on   

原文地址:http://www.cnblogs.com/lienus/p/4167701.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!