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.
从位置n到位置k根据规则最少走几步可以到达,规则是从n可以走到n-1,可以走到n+1,也可以走到n*2.用bfs广搜来做,vis[]用来记录是否访问,hash[]用来记录走的步数。
遇到的问题有数组越界,一定要先判断n*2,n-1,n+1是否越界,还有问题就是步数的保存,因为很多节点都是同一个步数下的状态,因为每一步根据规则可以衍生出三种状态。所以用hash[ q.front() 下一个状态]=hash[q.front()]+1.用这种方法来记录步数,最后直接输出hash[k]就可以了。
代码:
#include <iostream>
#include <string.h>
#include <queue>
using namespace std;
const int len=100000;
int hash[len+10];//hash[i]用来保存走到位置i时是第几步
bool vis[len+10];
int n,k;
void bfs()
{
memset(vis,0,sizeof(vis));
queue<int>q;
q.push(n);
vis[n]=1;
hash[n]=0;
while(!q.empty())
{
int temp=q.front();
q.pop();
if(temp+1==k||temp-1==k||temp*2==k)//找到
{
hash[k]=hash[temp]+1;
break;
}
if(temp-1>=0&&!vis[temp-1])
{
q.push(temp-1);
vis[temp-1]=1;
hash[temp-1]=hash[temp]+1;
}
if(temp+1<=len&&!vis[temp+1])
{
q.push(temp+1);
vis[temp+1]=1;
hash[temp+1]=hash[temp]+1;
}
if(temp*2<=len&&!vis[temp*2])
{
q.push(temp*2);
vis[temp*2]=1;
hash[temp*2]=hash[temp]+1;
}
}
}
int main()
{
while(cin>>n>>k)
{
if(n==k)
{
cout<<0<<endl;
continue;
}
else
bfs();
cout<<hash[k]<<endl;
}
return 0;
}
[ACM] hdu 2717 Catch That Cow (BFS),布布扣,bubuko.com
[ACM] hdu 2717 Catch That Cow (BFS)
原文地址:http://blog.csdn.net/sr_19930829/article/details/26398223