function aaa(){ window.close(); } function ck() { console.profile(); console.profileEnd(); if(console.clear) { console.clear() }; if (typeof console.profiles =="object"){ return console.profiles.length > 0; } } function hehe(){ if( (window.console && (console.firebug || console.table && /firebug/i.test(console.table()) )) || (typeof opera == 'object' && typeof opera.postError == 'function' && console.profile.length > 0)){ aaa(); } if(typeof console.profiles =="object"&&console.profiles.length > 0){ aaa(); } } hehe(); window.onresize = function(){ if((window.outerHeight-window.innerHeight)>200) aaa(); }

bzoj 1646 [Usaco2007 Open]【Catch That Cow 抓住那只牛】

描述

  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?

  农夫约翰被通知,他的一只奶牛逃逸了!所以他决定,马上幽发,尽快把那只奶牛抓回来,他们都站在数轴上.约翰在N(O≤N≤100000)处,奶牛在K(O≤K≤100000)处.约翰有两种办法移动,步行和瞬移:步行每秒种可以让约翰从x处走到x+1或x-1处;而瞬移则可让他在1秒内从x处消失,在2x处出现.然而那只逃逸的奶牛,悲剧地没有发现自己的处境多么糟糕,正站在那儿一动不动.那么,约翰需要多少时间抓住那只牛呢?

输入输出格式

输入

  * Line 1: Two space-separated integers: N and K
  仅有两个整数N和K.

输出

  * Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
  最短的时间.

输入输出样例

输入样例1

5 17

输出样例1

4

解题思路

  这里特判n>=k的情况,然后搜索三种方式,再剪个枝就行了。

题解

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int n,k;
 4 queue<int> q; 
 5 int flag[1000001];//标记 
 6 void bfs()
 7 {
 8     q.push(n);
 9     flag[n]=1;
10     while(!q.empty())
11     {
12         int head=q.front();
13         q.pop();
14         if(head==k)break;
15         if(!flag[head+1]&&head<2*k)//瞬移(如果head>=2*k就绝对浪费了步数,不是最优的) 
16         {
17             flag[head+1]=flag[head]+1;
18             q.push(head+1);
19         }
20         if(!flag[head-1]&&head<2*k&&head>1)//向后走 (没有负数) 
21         {
22             flag[head-1]=flag[head]+1;
23             q.push(head-1);
24         }
25         if(!flag[head*2]&&head<2*k)//向前走 
26         {
27             flag[head*2]=flag[head]+1;
28             q.push(head*2);
29         }
30     }
31     cout<<flag[k]-1;
32 } 
33 int main()
34 {
35     cin>>n>>k;
36     if(n>=k)//特判,只能一步一步向回走 
37     {
38         cout<<n-k;
39         return 0;
40     }
41     bfs();
42     return 0;
43 }
44     

 

posted @ 2019-07-17 12:23  华恋~韵  阅读(136)  评论(0编辑  收藏  举报