Skip to content

Instantly share code, notes, and snippets.

@anurudhp
Last active July 15, 2021 23:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anurudhp/1ecf14f1211c71cd5c99537fad13fecd to your computer and use it in GitHub Desktop.
Save anurudhp/1ecf14f1211c71cd5c99537fad13fecd to your computer and use it in GitHub Desktop.
Diameter using single DFS in O(n).
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 1;
VI adj[N];
int mdep[N];
int diam = 0;
void dfs(int u, int p = -1, int d = 0, int pdep = 0) {
mdep[u] = d;
diam = max(diam, pdep + d);
for (int v : adj[u]) {
if (v == p) continue;
dfs(v, u, d + 1, pdep);
mdep[u] = max(mdep[u], mdep[v]);
pdep = max(pdep, mdep[u] - 2 * d);
}
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n - 1; i++) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
dfs(1);
cout << diam << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment