noi.openjudge——2971 抓住那头牛

http://noi.openjudge.cn/ch0205/2971/
总时间限制: 
2000ms
 
内存限制: 
65536kB
描述

农夫知道一头牛的位置,想要抓住它。农夫和牛都位于数轴上,农夫起始位于点N(0<=N<=100000),牛位于点K(0<=K<=100000)。农夫有两种移动方式:

1、从X移动到X-1或X+1,每次移动花费一分钟
2、从X移动到2*X,每次移动花费一分钟
 
假设牛没有意识到农夫的行动,站在原地不动。农夫最少要花多少时间才能抓住牛?
输入
两个整数,N和K
输出
一个整数,农夫抓到牛所要花费的最小分钟数
样例输入
5 17
样例输出
4


BFS
 1 #include <iostream>
 2 
 3 #define maxn 100000
 4 
 5 using namespace std;
 6 
 7 int s,t,head,tail;
 8 
 9 bool vis[maxn+5];
10 
11 struct node
12 {
13     int now,val;
14 }que[maxn+5];
15 
16 int main()
17 {
18     cin>>s>>t;
19     que[tail].now=s;
20     que[tail++].val=0;
21     vis[s]=1;
22     while(head<tail)
23     {
24         int now=que[head].now,val=que[head].val;
25         if(now==t)
26         {
27             cout<<val;
28             return 0;
29         }
30         if(!vis[now*2]&&now*2<=maxn&&now)
31         {
32             que[tail].now=now*2;
33             que[tail++].val=val+1;
34             vis[now*2]=1;
35         }
36         if(!vis[now+1]&&now+1<=maxn&&now<t)
37         {
38             que[tail].now=now+1;
39              que[tail++].val=val+1;
40              vis[now+1]=1;
41              
42         }
43         if(!vis[now-1]&&now>0)
44         {
45             que[tail].now=now-1;
46              que[tail++].val=val+1;
47              vis[now-1]=1;
48         }
49         head++;
50     }
51     return 0;
52 }
无限ER
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstdlib>
 4 
 5 using namespace std;
 6 
 7 int n,k;
 8 int b[100005];
 9 
10 struct sop
11 {
12     int sum;
13     int step; 
14 }queue[100005];
15 
16 void bfs(int n,int k)
17 {
18     int head=0;
19     int tail=1;
20     queue[tail].sum=n;
21     queue[tail].step=0;
22     b[n]=1;
23     while(head<tail)
24     {
25         head++;
26         if(queue[head].sum==k)
27         {
28             cout<<queue[head].step;
29             return;
30         }
31         if(!b[queue[head].sum*2]&&(queue[head].sum*2<=100000)&&(queue[head].sum!=0))
32         {
33             tail++;
34             queue[tail].sum=queue[head].sum*2;
35             b[queue[head].sum*2]=1;
36             queue[tail].step=queue[head].step+1;
37         } 
38         if(!b[queue[head].sum+1]&&(queue[head].sum+1<=100000)&&(queue[head].sum+1<=k))
39         {
40             tail++;
41             queue[tail].sum=queue[head].sum+1;
42             b[queue[head].sum+1]=1;
43             queue[tail].step=queue[head].step+1;
44         } 
45         if(!b[queue[head].sum-1]&&(queue[head].sum-1>=0))
46         {
47             tail++;
48             queue[tail].sum=queue[head].sum-1;
49             b[queue[head].sum-1]=1;
50             queue[tail].step=queue[head].step+1;
51         }
52     } 
53     return ; 
54 }
55 
56 int main()
57 {
58     cin>>n>>k;
59     
60     bfs(n,k);
61     return 0; 
62 }
AC题解
——每当你想要放弃的时候,就想想是为了什么才一路坚持到现在。
原文地址:https://www.cnblogs.com/Shy-key/p/6683713.html