http://poj.org/problem?id=3278

大意是说牛在原地不动,他在某点去抓牛,他有两种方式可以走,第一种走一步,往前往后都可,第二种是走现在所在点的两倍的数目。只要能够刚好到达牛所在的那个点就行了。

因为题目中给了提示用广搜BFS,在三个方向上广搜就可以,这个题是借鉴了某位大神的才写出来的http://blog.csdn.net/ffq5050139/article/details/7341377

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<queue>
 4 #include<iostream>
 5 const int MAXN=100010;
 6 using namespace std;
 7 int vis[MAXN];
 8 int step[MAXN];
 9 queue<int>q;
10 int bfs(int n,int k)
11 {
12     int head,next;
13     q.push(n);
14     vis[n]=1;
15     step[n]=0;
16     while(!q.empty())
17     {
18         head=q.front();
19         q.pop();
20         for(int i=0;i<=2;i++)
21         {
22             if(i==0) next=head-1;
23             else if(i==1) next=head+1;
24             else if(i==2) next=head*2;
25             if(next>MAXN||next<0)//边界
26             continue;
27             if(!vis[next])//重点,走过的可以不用加进去了
28             {
29                 q.push(next);
30                 step[next]=step[head]+1;
31                 vis[next]=1;
32             }
33             if(next == k)
34             return step[next];
35         }
36     }
37 }
38 int main()
39 {
40     int n,k;
41     scanf("%d %d",&n,&k);
42     if(n>=k)
43     printf("%d\n",n-k);
44     else
45     {
46         printf("%d\n",bfs(n,k));
47     }
48     return 0;
49 }
View Code

 

posted on 2013-07-29 19:12  枫、  阅读(259)  评论(0)    收藏  举报