题意:输入两个数,start,end。从开始通过三种更新到end需要多少次。典型的广搜
链接:http://acm.hdu.edu.cn/showproblem.php?pid=2717
View Code
#include <iostream> #include <queue> using namespace std; int n,m; #define MAX 200000+10 bool used[MAX]; struct node { int n; int x; }; int bfs(int start) { queue<node>q; node temp; memset(used,false,sizeof(used)); temp.n=start; temp.x=0; used[start]=true; q.push(temp); while(!q.empty()) { node type=q.front(); q.pop(); for(int i=0;i<3;i++) { node flag=type; if(i==0) { flag.n=type.n+1; } if(i==1) { flag.n=type.n-1; } if(i==2) { flag.n=type.n*2; } flag.x=type.x+1; if(flag.n>=0&&flag.n<=100000&&!used[flag.n])//判断是否超出所要求的范围,这里坑了好几次。 { if(flag.n==m) { return flag.x; } used[flag.n]=true; q.push(flag); } } } return 0; } int main() { while(scanf("%d%d",&n,&m)!=EOF) { if(n==m)//当n==m时,不处理就会出错 { printf("0\n"); continue; } printf("%d\n",bfs(n)); } return 0; }
两个注意:
注意一:更新数应该大于0且小于100000;
注意二:start==end的情况,直接输出0,不然会出错。