版权声明:iQXQZX https://blog.csdn.net/Cherishlife_/article/details/85995607
广度优先搜索练习之神奇的电梯
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
有一座已知层数为n的高楼,这座高楼的特殊之处在于只能靠电梯去上下楼,所以要去到某一层要非常耽误时间,然而更悲哀的是,这座高楼的电梯是限号的,小鑫最开始的时候在1层,他想去第x层,问题是他最起码要经过多少层(包含第x层)才能到达第x层。
Input
多组输入。
第一行是三个正整数n,m,q。分别代表楼的总层数,给定的m条信息和q次查询。
接下来的m行,每行的第一个整数pos代表这是第pos层的电梯,第二个数代表从这一层可以去的楼层总共有num个,之后的num个数字代表从第pos层代表可以去的楼层。
最后的q行,每行一个整数代表小鑫想去的楼层号码。
1<=m,pos,num<=n<=200
1<=q<=20
Output
对于每次询问输出一个整数,占一行。代表如果要去某个楼层最少要经过多少层,如果到不了的话就输出-1。
Sample Input
10 4 3 1 2 6 7 3 4 4 6 8 10 5 2 2 3 7 3 10 5 6 4 5 9
Sample Output
5 3 -1
Hint
Source
Casithy
第一次使用STL库的vector (容器) 可变数组 创建图
关于vector的详细操作 请看另一篇博客
https://blog.csdn.net/Cherishlife_/article/details/85859846
#include <bits/stdc++.h>
using namespace std;
struct node
{
int num; // 楼层
int step; // 次数
};
vector<int> gra[205]; // 用vector 创建图 (可变数组 比稀疏邻接矩阵更节省空间)
int cat[205]; // 标记数组
int n, m, q;
int bfs(int i, int wantto)
{
cat[i] = 1;
node p = {i, 1};
queue<node> q;
q.push(p);
while (!q.empty())
{
node temp = q.front();
q.pop();
if (temp.num == wantto)
return temp.step;
vector<int>::iterator it; // it指针指向第一个元素
for (it = gra[temp.num].begin(); it < gra[temp.num].end(); it++)
{
node t = {*it, temp.step + 1};
if (!cat[*it])
{
cat[*it] = 1;
q.push(t);
}
}
/*****************或者如下写法*******************/
// for (int i = 0; i < gra[temp.num].size(); i++)
// {
// node t = {gra[temp.num][i], temp.step + 1};
// if (!cat[gra[temp.num][i]])
// {
// cat[gra[temp.num][i]] = 1;
// q.push(t);
// }
// }
}
return -1;
}
int main()
{
int num, pos, to;
while (cin >> n >> m >> q)
{
for (int i = 0; i < 205; i++) // 每次初始化否则必错
gra[i].clear();
for (int i = 0; i < m; i++)
{
cin >> pos >> num;
while (num--)
{
cin >> to;
gra[pos].push_back(to); // 这句等价于 gra[pos][cnt++] = to;
}
}
int wantto;
while (q--)
{
cin >> wantto;
memset(cat, 0, sizeof(cat));
cout << bfs(1, wantto) << endl;
}
}
return 0;
}