bfs 抓住那头牛

这是题目呀!http://ybt.ssoier.cn:8088/problem_show.php?pid=1253

算法分析:看到这道题目要求为最短时间,就可以判断用bfs(按照距开始状态由远及近的顺序进行搜索),而不是dfs。

     在搜索过程中还可能遇到重复搜索的结果,这时我们就可以引入一个队列,使得已搜过的节点入队,再以此为下一层的父节点出队,以此往复。

#include <iostream>

#include<cstdio>

#include <queue>
#define maxx 100001
using namespace std;

int n,k,now;
int ans[maxx],a[3];//ans数组还要标记访问
queue<int>q;

void bfs(){

fill(ans,ans+maxx,-1); //数组初始化的另一种方法
q.push(n);
ans[n] = 0;
while (!q.empty()){
now = q.front();//每次取前端的状态
q.pop();
if (now == k) break;//此时为终点,跳出
a[0] = now - 1;
a[1] = now + 1;
a[2] = now * 2;
for (int i = 0;i < 3;i++){
if (a[i] >= 0 && a[i] <maxx && ans[a[i]] == -1){
q.push(a[i]);
ans[a[i]] = ans[now] + 1;
}
}
}
cout << ans[k] << endl;
}

猜你喜欢

转载自www.cnblogs.com/lalalalala1279/p/10884516.html