- 总时间限制:
- 2000ms
- 内存限制:
- 65536kB
- 描述
-
农夫知道一头牛的位置,想要抓住它。农夫和牛都位于数轴上,农夫起始位于点N(0<=N<=100000),牛位于点K(0<=K<=100000)。农夫有两种移动方式:
1、从X移动到X-1或X+1,每次移动花费一分钟2、从X移动到2*X,每次移动花费一分钟假设牛没有意识到农夫的行动,站在原地不动。农夫最少要花多少时间才能抓住牛? - 输入
- 两个整数,N和K
- 输出
- 一个整数,农夫抓到牛所要花费的最小分钟数
- 样例输入
-
5 17
- 样例输出
-
4
深搜 炸:#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> using namespace std; const int N=100010; bool vis[N]; int people; int milk; int answer=99999999; int nowans=0; inline int read() { int x=0;char c=getchar(); while(c<'0'||c>'9')c=getchar(); while(c>='0'&&c<='9')x=x*10+c-'0',c=getchar(); return x; } void dfs(int nowpeople) { vis[nowpeople]=1; if(nowpeople==milk) { answer=min(answer,nowans); return ; } if(!vis[nowpeople+1]&&nowpeople+1>0&&nowpeople+1<=milk+1) { nowans++; vis[nowpeople+1]=1; dfs(nowpeople+1); nowans--; vis[nowpeople+1]=0; } if(!vis[nowpeople-1]&&nowpeople-1>0&&nowpeople-1<=milk+1) { nowans++; vis[nowpeople-1]=1; dfs(nowpeople-1); nowans--; vis[nowpeople-1]=0; } if(!vis[nowpeople*2]&&nowpeople*2>0&&nowpeople*2<=milk+1) { nowans++; vis[nowpeople*2]=1; dfs(nowpeople*2); nowans--; vis[nowpeople*2]=0; } } int main() { people=read(); milk=read(); dfs(people); printf("%d",answer); return 0; }
广搜:
#include<iostream> #include<cstdio> #include<algorithm> #include<queue> #include<cstdlib> using namespace std; const int N=100010; struct node{ int x,step; }now,nxt,top; int peo,milk; bool vis[N]; queue<node>q; inline int read() { int x=0;char c=getchar(); while(c<'0'||c>'9')c=getchar(); while(c>='0'&&c<='9')x=x*10+c-'0',c=getchar(); return x; } inline void bfs(int start) { now.x=start; now.step=0; q.push(now); while(!q.empty()) { top=q.front(); q.pop(); int x=top.x; if(x==milk) { printf("%d ",top.step); exit(0); } if(x+1>=0&&x+1<=100000&&!vis[x+1]) { vis[x+1]=1; nxt.x=x+1; nxt.step=top.step+1; q.push(nxt); } if(x-1>=0&&x-1<=100000&&!vis[x-1]) { vis[x-1]=1; nxt.x=x-1; nxt.step=top.step+1; q.push(nxt); } if(x*2>=0&&x*2<=100000&&!vis[x*2]) { vis[x*2]=1; nxt.x=x*2; nxt.step=top.step+1; q.push(nxt); } } } int main() { peo=read(); milk=read(); bfs(peo); return 0; }