1. 程式人生 > >SDUTOJ3468_廣度優先搜尋練習之神奇的電梯(BFS + 用vector建圖)

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