L3-008 喊山

題解ios

  這一題的正解是鄰接表 + bfs。spa

       若是不用鄰接表,而用鄰接矩陣,在bfs搜索時,會出現大量的無用搜索,由於你也不知道a - b是否相連,因此你就要枚舉1 - n來判斷是否和a相連就形成了TLE了。code

       而後有一個細節,我卡了好久,我是直接按照搜索層次求該層的最小值,可是有一個答案Error了,可是用一個d[]來記錄步數,找出最大的距離就AC了,以前可能由於成環狀形成該層距離不必定最長(猜想)。blog

  

#include <iostream>
#include <queue>
#include <vector>
#include <cstring>
#include <algorithm> 
using namespace std;

const int MAXN = 10010;
int n, m, k;
vector <int> q[MAXN];

void bfs(int x)
{
    queue <int> qx;
    bool st[MAXN];
    int d[MAXN];
    memset(d, 0, sizeof(d));
    memset(st, false, sizeof(st));
    qx.push(x);
    st[x] = true;    
    while (!qx.empty()) {
        int a = qx.front();
        bool mark = false;
        qx.pop();
        for (int i = 0; i < q[a].size(); ++i) {
            if (!st[q[a][i]]) {
                d[q[a][i]] = d[a] + 1;
                qx.push(q[a][i]);
                st[q[a][i]] = true;
            }
        }
    }
    int maxx = 0, p = 0;
    for (int i = 1; i <= n; ++i) {
        if (d[i] > maxx) {
            maxx = d[i];
            p = i;
        }
    }
    cout << p << endl;
}
  
int main()
{
    cin >> n >> m >> k;
    while (m--) {
        int a, b;
        cin >> a >> b;
        //此爲無向圖,採用鄰接表的存儲方式
        q[a].push_back(b);
        q[b].push_back(a); 
    }
    while (k--) {
        int x;
        cin >> x;
        bfs(x);
    }
    return 0;
}
相關文章
相關標籤/搜索