POJ 3278(bfs)

虽然是水题,但要注意数组的越界和vis的使用,不然就RE、TLE

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
using namespace std;
#define inf 0x3f3f3f3f
#define ll long long
const int maxn=100005;
const double eps=1e-8;
const double PI = acos(-1.0);
struct node
{
    int d,time;
    node(int a,int b):d(a),time(b) {}
    node() {}
};
int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(0);
    std::cout.tie(0);
    int n,k;
    while(cin>>n>>k)
    {
        bool vis[100005]= {0};
        queue<node> q;
        node s;
        s.d=n;
        s.time=0;
        q.push(s);
        vis[n]=1;
        while(!q.empty())
        {
            node t=q.front();
            if(t.d==k)
            {
                cout<<t.time<<endl;
                break;
            }
            q.pop();
            int flag=0;
            for(int i=0; i<3; i++)
            {
                if(i==0&&t.d+1<maxn&&!vis[t.d+1])
                {
                    node a(t.d+1,t.time+1);
                    q.push(a);
                    if(a.d==k)
                    {
                        cout<<a.time<<endl;
                        flag=1;
                        break;
                    }
                    vis[t.d+1]=1;
                }
                else if(i==1&&t.d>0&&!vis[t.d-1])
                {
                    node a(t.d-1,t.time+1);
                    q.push(a);
                    if(a.d==k)
                    {
                        cout<<a.time<<endl;
                        flag=1;
                        break;
                    }
                    vis[t.d-1]=1;
                }
                else if(i==2&&t.d*2<maxn&&!vis[t.d*2])
                {
                    node a(t.d*2,t.time+1);
                    q.push(a);
                    if(a.d==k)
                    {
                        cout<<a.time<<endl;
                        flag=1;
                        break;
                    }
                    vis[t.d*2]=1;
                }

            }
            if(flag)
                break;
        }
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值