想看更多的解题报告: http://iyenn.com/rec/1824570.html
转载请注明出处:http://blog.csdn.net/wangjian8006
题目大意:
输入两个数n,k两个数,问从n到k最少经过多少步,对于一个数x有三种走法,x-1,x+2,2*x
代码:
- #include
- #include
- using namespace std;
- #define MAXV 200000
-
- int key[MAXV];
- bool dis[MAXV];
-
-
- int bfs(int first,int last){
- int v;
- queue <int>q;
-
- memset(dis,false,sizeof(dis));
- memset(key,0,sizeof(key));
-
- q.push(first);
- key[first]=0;
- dis[first]=true;
-
- while(!q.empty()){
- v=q.front();
- q.pop();
-
- if(v==last) return key[v];
-
- if((v-1)>=0 && (v-1)
-1]) {key[v-1]=key[v]+1;dis[v-1]=true;q.push(v-1);} - if((v+1)>=0 && (v+1)
1]) {key[v+1]=key[v]+1;dis[v+1]=true;q.push(v+1);} - if((v*2)>=0 && (v*2)
2*v]) {key[v*2]=key[v]+1;dis[v*2]=true;q.push(v*2);} - }
- }
-
- int main(){
- int n,k;
- while(scanf("%d%d",&n,&k)!=EOF){
- printf("%d\n",bfs(n,k));
- }
- return 0;
- }
评论记录:
回复评论: