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;
}

 

上一篇:poj 2243(bfs结构体)


下一篇:poj 3984(模板题,bfs)