本文主要是介绍HDU 1548 广搜,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
<a target=_blank href="http://acm.hdu.edu.cn/showproblem.php?pid=1548">原题链接</a>
/*广度优先搜索题到每一层楼都可以上楼和下楼,但要注意的是不能小于1当然也不能大于n每到一层楼就把层数放在队列里,取出层数后又去掉然后通过每个层数生成子节点进行搜索
*/
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<algorithm>
#include<cstdlib>
#include<queue>
#define INF 0xfffffff
using namespace std;
int time[205], upd[205][2];
int n, a, b;int bfs()
{memset(time,-1,sizeof(time));queue<int> p;//建立队列p.push(a);//将开始所在的楼层添加到队列中time[a] = 0;//用time保存到达所在楼层按电梯的次数,在开始所在楼层时,当然赋值为0int t, next;while(!p.empty())//只有队列非空才进行搜索{t = p.front();//获取队头p.pop();//去队头if(t == b) return time[t];//当队头等于b时,到达,返回到达所在楼层按电梯的次数for(int i = 0; i < 2; i++){next = t + upd[t][i];//上下楼if(next>=1&&next<=n&&time[next]==-1)//所到楼层不能小于1也不能大于n{time[next] = time[t] + 1;//到达满足条件的楼层,所在楼层次数加一p.push(next);//将所在楼层添加到队列中}}}return -1;//如果到不了指定楼层,返回-1
}int main()
{while(cin >> n && n){cin >> a >> b;for(int i = 1; i <= n; i++){cin >> upd[i][0];upd[i][1] = -upd[i][0];//upd[i][0]为上楼,upd[i][1]为下楼}cout << bfs() << endl;}return 0;
}
这篇关于HDU 1548 广搜的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!