HDU 2717 Catch That Cow [BFS]

#Description
一个数轴,给定一个起点,一个终点,然后单位时间内可以,到x+1,x-1,2x的地方,求最小花多少时间到
#Algorithm
BFS
#Hint
又是多组数据
#Code

#include <iostream>
#include <queue>
using namespace std;
const int maxn = 100009;
struct V
{
  int x, s;
};
int main()
{
  int n, k;
  while (cin >> n >> k)
  {
    queue<V> q;
    V t;
    t.x = n;
    t.s = 0;
    q.push(t);
    int ans;
    bool a[maxn] = {false};
    while (!q.empty())
    {
      V now = q.front();
      int x = now.x, s = now.s;
      a[x] = true;
      q.pop();
      if (x == k)
      {
        ans = s;
        break;
      }
      V next;
      next.x = x - 1;
      next.s = s + 1;
      if (next.x >= 0 && !a[next.x]) q.push(next);
      next.x = x + 1;
      if (next.x <= maxn && !a[next.x]) q.push(next);
      next.x = 2 * x;
      if (next.x <= maxn && !a[next.x]) q.push(next);
    }
    cout << ans << endl;
  }
}

猜你喜欢

转载自blog.csdn.net/YYecust/article/details/50813990
今日推荐