L3-008 喊山

题解

  这一题的正解是邻接表 + bfs。

       如果不用邻接表,而用邻接矩阵,在bfs搜索时,会出现大量的无用搜索,因为你也不知道a - b是否相连,所以你就要枚举1 - n来判断是否和a相连就造成了TLE了。

       然后有一个细节,我卡了很久,我是直接按照搜索层次求该层的最小值,但是有一个答案Error了,但是用一个d[]来记录步数,找出最大的距离就AC了,之前可能因为成环状造成该层距离不一定最长(猜测)。

  

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

 

posted @ 2020-10-25 22:27  Fool_one  阅读(118)  评论(0编辑  收藏  举报