poj 3278 Catch That Cow 【bfs】

来源:互联网 发布:美工设计班 编辑:程序博客网 时间:2024/06/09 18:32

Catch That Cow
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 84785 Accepted: 26625

Description

Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.

* Walking: FJ can move from any point X to the points - 1 or + 1 in a single minute
* Teleporting: FJ can move from any point X to the point 2 × X in a single minute.

If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?

Input

Line 1: Two space-separated integers: N and K

Output

Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.

Sample Input

5 17

Sample Output

4

Hint

The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.

AC:

# include <stdio.h># include <string.h># define M 100005struct QUE{int x;int f;int s;} q[M];int head, tail;int n, k;int book[M];int tx;void bfs(){head = 1;tail = 1;memset(book, 0, sizeof(book));q[head].x = n;q[head].s = 0;tail ++;book[n] = 1;while (head < tail){for (int i = 0; i < 3; i++){switch(i){case 1 :tx = q[head].x + 1;break;case 2 :tx = q[head].x - 1;break;case 0 :tx = q[head].x * 2;break;}if (tx < 0 || tx > 100000){continue;}if (!book[tx]){book[tx] = 1;q[tail].x = tx;q[tail].s = q[head].s + 1;tail ++;}if (tx == k){/*int t = tail - 1;while (t){printf("%d ", q[t].x);t = q[t].f;}printf("\n");*/printf("%d\n", q[tail - 1].s);return ;}}head ++;}}int main(void){while (~scanf("%d %d", &n, &k)){if (n >= k) //当n大于k 不需要前移 不需要传送 只要不断后移即可{printf("%d\n", n - k);}else{bfs();}}return 0;}


0 0
原创粉丝点击