题目连接:http://acm.pku.edu.cn/JudgeOnline/problem?id=3278
挺简单的一道广搜题目
#include<iostream>
using namespace std;
#define MAX 100001
struct Node
{
int data;
int step;
};
Node q[MAX];
int hd,tl;
bool visit[MAX];
int BFS(Node& s,Node& d)
{
if(s.data == d.data)
return 0;
Node cur,next;
cur.data = s.data;
cur.step = 0;
hd = tl = 0;
memset(visit,false,sizeof(visit));
q[tl++] = cur;
visit[cur.data] = true;
while(tl != hd)
{
cur = q[hd++];
next.data = cur.data + 1;
next.step = cur.step + 1;
if(next.data < MAX && !visit[next.data])
{
if(next.data == d.data)
return next.step;
visit[next.data] = true;
q[tl++] = next;
}
next.data = cur.data - 1;
next.step = cur.step + 1;
if(!visit[next.data])
{
if(next.data == d.data)
return next.step;
visit[next.data] = true;
q[tl++] = next;
}
next.data = cur.data * 2;
next.step = cur.step + 1;
if(next.data < MAX && !visit[next.data])
{
if(next.data == d.data)
return next.step;
visit[next.data] = true;
q[tl++] = next;
}
}
}
int main()
{
freopen("in.txt","r",stdin);
Node s,d;
while(cin >> s.data >> d.data)
{
cout << BFS(s,d) << endl;
}
return 0;
}