5 17
4HintThe fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.
* Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute
* Teleporting: FJ can move from any point X to the point 2 × X in a single minute.//距离是上一段距离的2倍;
程序写好后,提交时发现编译错误,经过查找,发现结构体变量stu now,next;从全局变量变成函数bfs里的变量后在杭电上提交正确
#include<stdio.h> #include<cstring> #include<queue> using namespace std; int n,k; int a[200005]; struct stu{ int on; int step; }; //struct node //{ // int on, step; // friend bool operator < (node a, node b) // { // return a.on > b.on; // } //}; //priority_queue<node>q; queue<stu>q; //priority_queue<stu>q; //int M=100004; //int IN=1000000; int bfs() { stu now,next; while(!q.empty()) q.pop(); now.on=n; now.step=0; a[now.on]=1; q.push(now); while(!q.empty()) { now=q.front(); q.pop(); // next.on=now.on; // next.step=now.step; for(int i=0;i<3;i++) { if(i==0) next.on=now.on+1; if(i==1) next.on=now.on-1; if(i==2) next.on=now.on*2; next.step=now.step+1; if(next.on==k) return next.step; if(next.on<0||next.on>100000) continue; if(!a[next.on]) { a[next.on]=1; q.push(next); } } } } int main() { int h; while(scanf("%d%d",&n,&k)!=EOF) { memset(a,0,sizeof(a)); if(n<k) { h=bfs(); printf("%d\n",h); } if(n==k) printf("0\n"); if(n>k) printf("%d\n",n-k); } return 0; }
再贴一个简单代码:
#include<stdio.h> #include<cstring> #include<queue> using namespace std; int n,k; int a[200005]; struct stu{ int on; int step; }; int bfs(int n,int k) { queue<stu>q; stu now,next; now.on=n; now.step=0; a[now.on]=1; q.push(now); while(!q.empty()) { now=q.front(); q.pop(); if(now.on==k) return now.step; for(int i=0;i<3;i++) { if(i==0) next.on=now.on+1; if(i==1) next.on=now.on-1; if(i==2) next.on=now.on*2; if(a[next.on]||next.on<0||next.on>100000) continue; a[next.on]=1; next.step=now.step+1; q.push(next); } } } int main() { int h; while(scanf("%d%d",&n,&k)!=EOF) { memset(a,0,sizeof(a)); h=bfs(n,k); printf("%d\n",h); } return 0; }