标签:
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 71899 | Accepted: 22632 |
Description
Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.
* 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.
If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?
Input
Output
Sample Input
5 17
Sample Output
4
Hint
Source
大致题意:
给定两个整数n和k
通过 n+1或n-1 或n*2 这3种操作,使得n==k
输出最少的操作次数
代码一:C++STL&&bfs版本:
#include<cstdio> #include<iostream> #include<algorithm> #include<queue> using namespace std; #define N 100010 int step[N],vis[N]; queue<int>q; int bfs(int n,int k){ int now,next; step[n]=0; vis[n]=1; q.push(n); while(!q.empty()){ now=q.front(); q.pop(); for(int i=0;i<3;i++){ if(i==0) next=now-1; else if(i==1) next=now+1; else if(i==2) next=now*2; if(next<0||next>N) continue; if(!vis[next]){ vis[next]=1; q.push(next); step[next]=step[now]+1; } if(next==k) return step[next]; } } } int main(){ int n,k; scanf("%d%d",&n,&k); if(n>=k) printf("%d\n",n-k); else printf("%d\n",bfs(n,k)); return 0; }
代码二:C语言+bfs+模拟队列版本
#include<cstdio> #include<iostream> #include<algorithm> using namespace std; #define N 100010 struct node{ int x,step; }q[N]; int vis[N]; int bfs(int n,int k){ node now,next; int head=0,tail=1; q[head].x=n; q[head].step=0; vis[n]=1; while(head<tail){ now=q[head++]; for(int i=0;i<3;i++){ if(i==0) next.x=now.x-1; else if(i==1) next.x=now.x+1; else if(i==2) next.x=now.x*2; if(next.x<0||next.x>N) continue; if(!vis[next.x]){ vis[next.x]=1; next.step=now.step+1; q[tail++]=next; } if(next.x==k) return next.step; } } } int main(){ int n,k; scanf("%d%d",&n,&k); if(n>=k) printf("%d\n",n-k); else printf("%d\n",bfs(n,k)); return 0; }
3.xzc的代码 同代码一
#include<queue> #include<cstdio> #include<iostream> #include<algorithm> #define INF 100000+100 using namespace std; int n,N,vis[INF]; queue<int>que; void check(int x,int k) { if (x<0||x>INF) return; if (!vis[x]) vis[x]=vis[k]+1,que.push(x); } int bfs(int x) { que.push(x); while (!que.empty()) { int now=que.front(); check(now-1,now); check(now+1,now); check(now*2,now); if (vis[N]) return vis[N]; que.pop(); } } int main() { scanf("%d%d",&n,&N); if (n>=N) cout<<n-N<<endl; else cout<<bfs(n); }
注:hdu同题
http://acm.hdu.edu.cn/showproblem.php?pid=2717
是输入若干组数据
标签:
原文地址:http://www.cnblogs.com/shenben/p/5575387.html