AcWing 3699. 树的高度
原题链接
简单
作者:
王小强
,
2021-07-18 18:25:03
,
所有人可见
,
阅读 609
breadth_first_search_algorithm
#include <iostream>
#include <vector>
#include <deque>
using namespace std;
int breadth_first_search_algorithm(vector<vector<int>>& g, vector<int>& seen, int start) {
deque q{{start}};
seen[start] = 1; // mark as seen
int dist = 0;
while (not q.empty()) {
size_t s = q.size();
while (s--) {
const int curr = q.front(); q.pop_front();
for (const int nei : g[curr]) {
if (seen[nei]) continue;
q.emplace_back(nei);
seen[nei] = 1;
}
}
++dist;
}
return dist - 1;
}
int main(const int argc, const char** argv) {
int n, m, u, v;
cin >> n >> m;
vector<vector<int>> g(n + 1);
vector<int> seen(n + 1, 0);
for (int i = 0; i < n - 1; ++i) {
cin >> u >> v;
g[u].emplace_back(v);
g[v].emplace_back(u);
}
int distance = breadth_first_search_algorithm(g, seen, m);
cout << distance;
return 0;
}