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.
题意:
你在s点,奶牛在e点,奶牛不动,你每次能从x到x+1或x-1或2*x,要抓住奶牛,问最小步数。
思路:
bfs,利用一个队列,每次出队首nx,按照上述三种方法扩展节点tx,如果tx没有入队列,则入队列,直到e点入队列,这样能保证每一个点都能以最小的步数入队列,就能得到正确答案了。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <string>
#include <map>
#include <stack>
#include <vector>
#include <set>
#include <queue>
#pragma comment (linker,"/STACK:102400000,102400000")
#define maxn 1005
#define MAXN 100005
#define mod 1000000009
#define INF 0x3f3f3f3f
#define pi acos(-1.0)
#define eps 1e-6
typedef long long ll;
using namespace std;
int n,m,ans,cnt,tot,flag;
int vis[MAXN]; // 标记数组 并且记录每个点的步数
void bfs()
{
int i,j,t;
queue<int>q; // STL中的队列 当然也可以手写
memset(vis,-1,sizeof(vis)); // 初始化为-1
vis[n]=0; // 起点0步可以到达
q.push(n); // 起点入队
while(!q.empty())
{
int nx=q.front(); // 取出队首
q.pop(); // 队首出队
if(nx==m) // 如果为m 则找到奶牛
{
ans=vis[m];
return ;
}
if(nx>0&&vis[nx-1]==-1) // 扩展tx
{
int tx=nx-1;
vis[tx]=vis[nx]+1;
q.push(tx);
}
if(nx<=100000&&vis[nx+1]==-1) // 扩展tx
{
int tx=nx+1;
vis[tx]=vis[nx]+1;
q.push(tx);
}
if(2*nx<=100000&&vis[2*nx]==-1) // 扩展tx
{
int tx=nx*2;
vis[tx]=vis[nx]+1;
q.push(tx);
}
}
}
int main()
{
int i,j,t;
while(~scanf("%d%d",&n,&m))
{
bfs();
printf("%d\n",ans);
}
return 0;
}
周赛 1009 题解 hdu 2717 Catch That Cow (简单bfs),布布扣,bubuko.com
周赛 1009 题解 hdu 2717 Catch That Cow (简单bfs)
原文:http://blog.csdn.net/tobewhatyouwanttobe/article/details/20942657