题目:http://poj.org/problem?id=3278
AC代码(C++):
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <vector>
#include <queue>
#include <math.h>
#include <string>
#include <string.h>
#include <bitset>
#define INF 0xfffffff
#define MAXN 100005
using namespace std;
int n,k;
bool vis[MAXN];
int dist[MAXN];
void bfs() {
queue<int> q;
memset(vis,false,sizeof(vis));
vis[n] = true;
q.push(n);
int node;
while (!q.empty()) {
node = q.front();
q.pop();
if(node==k)return;
if(node>0&&vis[node-1]==false){
int tmp = node - 1;
dist[tmp] = dist[node]+1;
vis[tmp] = true;
q.push(tmp);
}
if(node<100000&&vis[node+1]==false){
int tmp = node + 1;
dist[tmp] = dist[node]+1;
vis[tmp] = true;
q.push(tmp);
}
if(2*node<=100000&&vis[node*2]==false){
int tmp = node * 2;
dist[tmp] = dist[node]+1;
vis[tmp] = true;
q.push(tmp);
}
}
}
int main(){
cin>>n>>k;
dist[n] = 0;
bfs();
cout<<dist[k];
}
总结: 很简单的广搜题. 注意不要越界就行.