SDUTOJ3468_广度优先搜索练习之神奇的电梯(BFS + 用vector建图)

                                              广度优先搜索练习之神奇的电梯

                                                                 Time Limit: 1000 ms Memory Limit: 65536 KiB

                                                                                       Submit Statistic

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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值