白云校区的奶牛
题目描述:
白云校区的食品学院最近养了只奶牛作奶品分析,最近下大雨奶牛趁机走丢了,小明被告知奶牛正在某位置上吃草,他很想尽快捉住它。假设小明刚开始在位置X (0 ≤X≤ 100,000),假设他与奶牛在一条直线上,奶牛在位置Y (0 ≤Y≤ 100,000)。小明有两种移动的方法:走路或瞬间移动:
(1)走路,小明可以在1秒钟从位置X 走到位置X – 1和位置X + 1;
(2)瞬间转移,小明可以在1秒钟从位置X 转移到位置2X。
由于奶牛不知道小明在追它,它在整个过程一动不动在吃草,问小明最短多长时间可以捉到这只奶牛。
输入格式:
有多行数据,每一行有两个整数X, Y
输出格式:
每一行输出小明捉住奶牛最短时间(秒)
样例输入:
5 17 1 2
样例输出:
4 1
提示:
在第一组测试数据中,小明最快捉住奶牛的路径是5-10-9-18-17, 一共用了4s时间。
时间限制:2000ms
空间限制:128MByte
#include <bits/stdc++.h> using namespace std; bool st[200005] = {}; int js(int mode, int now) { if(mode == 1) return now - 1; else if(mode == 2) return now + 1; else if(mode == 3) return now * 2; } int main() { int x, y, s, w, n, ans; while(scanf("%d%d", &x, &y) != EOF) { if(x > y){ printf("%d\n", x - y); continue; } for(int i = x / 2; i <= y + 1; i++) st[i] = 0; queue<int> q; q.push(x), q.push(0); while(!q.empty()){ w = q.front(); q.pop(); s = q.front(); q.pop(); if(w == y){ ans = s; break; } for(int i = 1; i <= 3; i++){ n = js(i, w); if(n > y + 1 || n < x / 2) continue; if(st[n]) continue; st[n] = 1; q.push(n), q.push(s +1); } } printf("%d\n", ans); } return 0; }