hdu_2717_Catch That Cow_bfs

题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=2717

题解:一维简单BFS,详细看代码,0ms。

 1 #include<cstdio>
 2 #include<queue>
 3 using namespace std;
 4 const int maxn=100002;
 5 bool v[maxn];
 6 int n,k;
 7 struct nd{
 8     int x,step;
 9 };
10 bool check(int x){
11     if(x<0||x>100000||v[x])return false;
12     else return true;
13 }
14 int bfs(int s){
15     for(int i=0;i<=100000;i++)v[i]=false;//初始化标记
16     queue<nd>Q;
17     nd S;
18     S.x=s,S.step=0;
19     v[s]=1;
20     Q.push(S);
21     while(!Q.empty()){
22         nd now=Q.front();Q.pop();
23         if(now.x==k)return now.step;
24         if(check(now.x+1)){
25             nd tmp;tmp.x=now.x+1,tmp.step=now.step+1;
26             v[tmp.x]=1;
27             Q.push(tmp);
28         }
29         if(check(now.x-1)){
30             nd tmp;tmp.x=now.x-1,tmp.step=now.step+1;
31             v[tmp.x]=1;
32             Q.push(tmp);
33         }
34         if(check(now.x*2)){
35             nd tmp;tmp.x=now.x*2,tmp.step=now.step+1;
36             v[tmp.x]=1;
37             Q.push(tmp);
38         }
39     }
40     return -1;
41 }
42 int main(){
43     while(~scanf("%d%d",&n,&k)){
44         if(n>=k){printf("%d\n",n-k);continue;}//剪枝
45         int ans=bfs(n);
46         printf("%d\n",ans);
47     }
48     return 0;
49 }
View Code

 

posted @ 2016-04-30 16:12  bin_gege  阅读(162)  评论(0编辑  收藏  举报