题目链接:http://poj.org/problem?id=3278
特别水的一道BFS...
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
using namespace std;
const int INF=0x3f3f3f3f;
const int maxn=100010;
int T,n,m,k;
int x[maxn];
bool vis[maxn];
struct node{
int x;
int step;
};
void bfs(){
queue<node>q;
node s,e;
s.x=n,s.step=0;
vis[s.x]=1;
q.push(s);
while(!q.empty()){
s=q.front();
q.pop();
if(s.x==k){
printf("%d\n",s.step);
return ;
}
e.step=s.step+1;
e.x=s.x-1;
if(e.x>=0&&!vis[e.x]){
vis[e.x]=1;
q.push(e);
}
e.x=s.x+1;
if(e.x<=100000&&!vis[e.x]){
vis[e.x]=1;
q.push(e);
}
e.x=2*s.x;
if((e.x>=0&&e.x<=100000)&&!vis[e.x]){
vis[e.x]=1;
q.push(e);
}
}
}
int main(){
#ifndef ONLINE_JUDGE
freopen("test.in","r",stdin);
freopen("test.out","w",stdout);
#endif
while(~scanf("%d%d",&n,&k)){
memset(vis,0,sizeof(vis));
bfs();
}
return 0;
}