| Time Limit: 2000MS | Memory Limit: 65536K | |
| Total Submissions: 43013 | Accepted: 13375 |
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 X - 1 or X + 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.
Source
都说这是一道水题,但这是我做的第一道关于bfs的题目,大家见谅哈。昨天刚看完bfs的基本内容的时候,再想做这题目,怎么也想不到这道题为何能用bfs解答。
后来看了一遍别人的源码,豁然开朗,发现bfs真是太神奇了。当然,感觉神奇的很大一部分原因是因为还没吃透bfs,想不通为什么能得到最优解。想了很久,又看了一些树的知识,终于想通了。其实,可以把这个问题看成一个图,这个图由100001个点连接而成(0~100000),而连接这些个点的桥则是那三个运算,加1,减1,乘2。例如,由5(父母)发散开三个儿子(6,4,10)。所以,点5与这三个点相连。因此,可以将N当成根,一点点伸展开。下面叙述一下bfs的算法实现细节,个人认为bfs的精髓在于将点分为三类,白色,灰色,黑色。先选如白色的点,然后将它染成灰色,之后查找他的邻居,将邻居放入一个先进先出队列,这个队列可以用c++stl中的queue实现,最后将这个点染为黑色。
理解了树的概念之后,本题就非常容易了,要求的结果就是深度。但是,今天编码的时候,没能自己想明白,还是参考了别人的源码,真是惭愧啊。其实,我觉得这道题目中深度也可以理解为一棵树。下面贴一下代码吧。
1 #include<iostream> 2 #include<queue> 3 using namespace std; 4 using std::queue; 5 const int MAX = 100000; 6 const int MIN = 0; 7 bool visited[100001]; 8 int N, K; 9 int depth[100001]; 10 queue<int> que; 11 int bfs(); 12 int main() 13 { 14 cin >> N >> K; 15 cout << bfs(); 16 system("pause"); 17 return 0; 18 } 19 int bfs() 20 { 21 memset(visited, false, sizeof(visited)); 22 que.push(N); 23 depth[N] = 0; 24 visited[N] = true; 25 while (!que.empty()) 26 { 27 int temp = que.front(); 28 que.pop(); 29 if (temp == K) 30 break; 31 else 32 { 33 int door1 = temp + 1; 34 int door2 = temp - 1; 35 int door3 = temp * 2; 36 if (door1 <= MAX && !visited[door1]){ 37 que.push(door1); 38 visited[door1] = true; 39 depth[door1] = depth[temp] + 1; 40 } 41 42 if (door2 >= MIN && !visited[door2]){ 43 que.push(door2); 44 visited[door2] = true; 45 depth[door2] = depth[temp] + 1; 46 } 47 if (door3 <= MAX && !visited[door3]){ 48 que.push(door3); 49 visited[door3] = true; 50 depth[door3] = depth[temp] + 1; 51 } 52 } 53 } 54 return depth[K]; 55 }
当然,这段代码违反了dry的原则,不够简洁,还是可以优化一下的。
注意这道题要把数组开到100001,因为是从0~100000,要是开到100000就等着RE吧。
浙公网安备 33010602011771号