Advertisement
Araf_12

tree_diameter & path

Oct 22nd, 2024
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 KB | None | 0 0
  1. pair<int, int> findDiameter(vector<vector<int>> &adj) {
  2.   int n = adj.size() - 1;
  3.   auto bfs = [&](int src) {
  4.     vector<int> dist(n + 1, -1);
  5.     queue<int> q;
  6.     dist[src] = 0;
  7.     q.push(src);
  8.     while (!q.empty()) {
  9.       int u = q.front();
  10.       q.pop();
  11.       for (int v : adj[u]) {
  12.         if (dist[v] == -1) {
  13.           dist[v] = dist[u] + 1;
  14.           q.push(v);
  15.         }
  16.       }
  17.     }
  18.     return dist;
  19.   };
  20.   vector<int> dist1 = bfs(1);
  21.   int node1 = max_element(dist1.begin(), dist1.end()) - dist1.begin();
  22.   vector<int> dist2 = bfs(node1);
  23.   int node2 = max_element(dist2.begin(), dist2.end()) - dist2.begin();
  24.   return make_pair(node1, node2);
  25. }
  26.  
  27.  
  28.  
  29. vector<int> getPath(int src, int dest, vector<vector<int>> &adj) {
  30.   int n = adj.size() - 1;
  31.   auto bfs = [&](int src) {
  32.     vector<int> dist(n + 1, -1), from(n + 1, -1);
  33.     queue<int> q;
  34.     dist[src] = 0;
  35.     q.push(src);
  36.     while (!q.empty()) {
  37.       int u = q.front();
  38.       q.pop();
  39.       for (int v : adj[u]) {
  40.         if (dist[v] == -1) {
  41.           dist[v] = dist[u] + 1;
  42.           from[v] = u;
  43.           q.push(v);
  44.         }
  45.       }
  46.     }
  47.     return from;
  48.   };
  49.   vector<int> from = bfs(src), path;
  50.   for (int node = dest; node != -1; node = from[node]) path.push_back(node);
  51.   reverse(path.begin(), path.end());
  52.   return path;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement