题目传送门:http://acm.hdu.edu.cn/showproblem.php?pid=2717
题目大意:给定两个x轴方向上的位置,农民有三种方式,用bfs找到最短路径即可.
AC代码:
#include <iostream>
#include <map>
#include <set>
#include <queue>
#include <string>
#include <vector>
#include <memory.h>
#include <algorithm>
#include <stdio.h>
using namespace std;
#define Size 100005
struct Node
{
int x;
int step;
};
int visit[Size];
int m, n;
int bfs()
{
queue<Node> temp;
Node s, now, next;
s.x = m;
s.step = 0;
temp.push(s);
visit[s.x] = 1;
while (!temp.empty())
{
now = temp.front();
temp.pop();
if (now.x == n)
{
return now.step;
}
for (int i = 0; i < 3; ++i)
{
if (i == 0)
next.x = now.x + 1;
else if (i == 1)
next.x = now.x - 1;
else if (i == 2)
next.x = 2 * now.x;
//位置合理且未被访问过.
if (next.x >= 0 && next.x < Size && visit[next.x] == 0)
{
visit[next.x] = 1;
next.step = now.step + 1;
temp.push(next);
}
}
}
return -1;
}
int main()
{
while (scanf("%d%d", &m,&n) != EOF)
{
if (m == n)
{
printf("0\n");
continue;
}
memset(visit, 0, sizeof(visit));
printf("%d\n", bfs());
}
return 0;
}