Openjudge 2971 grab the bull.

Source: Internet
Author: User

Total time limit:
2000ms
Memory Limit:
65536kB
Describe

The farmer knows the position of a bull and wants to catch it. Both the farmer and the ox are located on the axis, the farmer starts at point N (0<=n<=100000) and the ox is at point K (0<=k<=100000). Farmers have two ways of moving:

1. Move from X to X-1 or x+1, one minute per move 2, moving from X to 2*x, each move takes a minute Suppose the cow is not aware of the farmer's actions and stands still. How long does it take at least for the farmer to catch the bull?

Input
two integers, N and K
Output
an integer, the minimum number of minutes a farmer can take to catch a cow.
Sample input
5 17
Sample output
4

The ordinary BFS. Be careful to prune and open large arrays.

1#include <iostream>2#include <algorithm>3#include <cstdio>4#include <cmath>5 using namespacestd;6 intn,k;7 BOOLvis[300001];8 intpos[1000000];9 intstep[1000000];Ten voidBFS () { One     intHd=0, tl=1; Apos[++hd]=N; -step[hd]=0; -      while(hd<=TL) { the         intnow=POS[HD]; -         if(now==k) { -printf"%d\n", STEP[HD]); -             return; +         } -         intnext=now*2; +         if(next>=0&& next<=100000&&!Vis[next]) { Avis[next]=1; atpos[++tl]=Next; -step[tl]=step[hd]+1;} -next=now+1; -         if(next<=100000&&!Vis[next]) { -pos[++tl]=Next; -vis[next]=1; instep[tl]=step[hd]+1;} -next=now-1; to         if(next>=0&&!Vis[next]) { +vis[next]=1; -pos[++tl]=Next; thestep[tl]=step[hd]+1;} *hd++; $     }Panax Notoginseng } - intMain () { thescanf"%d%d",&n,&k); + BFS (); A     return 0; the}

Openjudge 2971 grab the bull.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.