Untitled
unknown
c_cpp
5 months ago
1.3 kB
8
Indexable
#include <iostream> #include <vector> #include <queue> using namespace std; pair<int, int> bfs(vector<vector<int>>& adj, int start, int n) { vector<int> dist(n + 1, -1); queue<int> q; q.push(start); dist[start] = 0; int maxDist = 0; int farthestNode = start; while (!q.empty()) { int curr = q.front(); q.pop(); for (int next : adj[curr]) { if (dist[next] == -1) { dist[next] = dist[curr] + 1; q.push(next); if (dist[next] > maxDist) { maxDist = dist[next]; farthestNode = next; } } } } return {farthestNode, maxDist}; } int find_max_transfer_time(vector<vector<int>>& adj, int n) { pair<int, int> end1 = bfs(adj, 1, n); pair<int, int> end2 = bfs(adj, end1.first, n); return end2.second; } int main() { int n, m; cin >> n >> m; vector<vector<int>> adj(n + 1); for (int i = 0; i < n-1; i++) { int u, v; cin >> u >> v; adj[u].push_back(v); adj[v].push_back(u); } cout << find_max_transfer_time(adj, n) << endl; return 0; }
Editor is loading...
Leave a Comment