Source: http://acm.pku.edu.cn/JudgeOnline/problem? Id = 3278
Solution report:
Breadth-first search, point X, points adjacent to the X-1, x + 1, 2 x
In this way, the vertex of N adjacent is searched from N, and then searched in this breadth until K is searched.
The obtained shortest path from N to k is the shortest time.
# Include <iostream> <br/> # include <queue> <br/> using namespace STD; </P> <p> int visit [200001]; <br/> int d [200001]; </P> <p> int BFS (int n, int K) <br/>{< br/> int S = N; <br/> visit [s] = 1; // gray <br/> d [s] = 0; <br/> queue <int> q; <br/> q. push (s); <br/> while (! Q. empty () <br/>{< br/> int u = Q. front (); <br/> q. pop (); <br/> int V [3]; <br/> V [0] = U-1; <br/> V [1] = u + 1; <br/> V [2] = 2 * U; <br/> for (INT I = 0; I <3; I ++) <br/> {<br/> If (V [I]> = 0 & V [I] <= 200001) <br/> {<br/> If (visit [V [I] = 0) <br/> {<br/> visit [V [I] = 1; <br/> d [V [I] = d [u] + 1; <br/> If (V [I] = k) <br/> return d [k]; <br/> q. push (V [I]); <br/>}< br/> visit [u] = 2; <br/>}< br/> return 0; <br/>}</P> <p> int main () <br/>{< br/> int N, k; <br/> CIN> N> K; <br/> cout <BFS (n, k) <Endl; </P> <p >}< br/>
Appendix:
Catch that cow
Time limit:2000 ms |
|
Memory limit:65536 K |
Total submissions:18412 |
|
Accepted:5657 |
Description
Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a pointN(0 ≤N≤ 100,000) on a number line and the cow is at a pointK(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 pointXTo the pointsX-1 orX+ 1 in a single minute
* Teleporting: FJ can move from any pointXTo the point 2 ×XIn 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:
NAnd
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.
Source