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