POJ 3278 Catch That Cow 【簡單bfs】
阿新 • • 發佈:2018-03-31
ems str empty next class pri eof color 奶牛
題目鏈接
題目大意:
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
POJ 3278 Catch That Cow 【簡單bfs】