poj 3278(bfs模板题)

#include<iostream>
#include<queue>
#include<cstring>
#include<cstdio>
using namespace std;
int n,k,ans;
int data[100005];
void bfs(){
    memset(data,-1,sizeof data);
    queue<int>q;
    q.push(n);
    data[n] = 0;
    while(!q.empty()){
        int t = q.front();q.pop();
        if(t==k){
            printf("%d\n",data[t]);
        }
        if(t-1>=0&&data[t-1]==-1){
            data[t-1] = data[t]+1;
            q.push(t-1);
        }
        if(t+1<=100000&&data[t+1]==-1){
            data[t+1] = data[t]+1;
            q.push(t+1);
        }
        if(t*2<=100000&&data[t*2]==-1){
            data[t*2] = data[t]+1;
            q.push(t*2);
        }
    }
}
int main(){
    scanf("%d%d",&n,&k);
    bfs();
    return 0;
}

 

posted @ 2021-08-11 16:53  智人心  阅读(46)  评论(0编辑  收藏  举报