题目大意:
FJ要抓奶牛。
开始输入N(FJ的位置)K(奶牛的位置)。
FJ有三种移动方法:1、向前走一步,耗时一分钟。
2、向后走一步,耗时一分钟。
3、向前移动到当前位置的两倍N*2,耗时一分钟。
问FJ抓到奶牛的最少时间。
PS:奶牛是不会动的。
#include <stdio.h> #include <string.h> #include <queue> #include <iostream> #include <algorithm> using namespace std; int vis[100005]; int n, k; struct dian { int x; long long s; }; queue<dian>q; long long bfs() { int i, j; dian now, next; while (!q.empty()) { now = q.front(); q.pop(); if (now.x == k)break; if (now.x - 1 >= 0 && !vis[now.x - 1]) { next.x = now.x - 1; vis[next.x] = 1; next.s = now.s + 1; q.push(next); } if (now.x + 1 <=100000 && !vis[now.x + 1]) { next.x = now.x + 1; vis[next.x] = 1; next.s = now.s + 1; q.push(next); } if (now.x *2 <= 100000 && !vis[now.x * 2]) { next.x = now.x * 2; vis[next.x] = 1; next.s = now.s + 1; q.push(next); } } return now.s; } int main() { int i, j; dian now; while (scanf("%d%d", &n, &k) != EOF) { memset(vis, 0, sizeof(vis)); while (!q.empty())q.pop(); now.x = n; now.s = 0; vis[now.x] = 1; q.push(now); printf("%lld\n", bfs()); } return 0; }
2018-03-31