1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| #include<bits/stdc++.h> typedef int int32; #define int long long using namespace std; const int N = 3e5 + 5; int n, m, root, num, dfn[N], low[N], dcc[N], cnt, dis; vector<pair<int,int>>nbr[N], new_nbr[N]; bool cut[N]; void tarjan(int x, int edge) { dfn[x] = low[x] = ++num; for (auto& y : nbr[x]) { auto& nxt = y.first, & w = y.second; if (!dfn[nxt]) { tarjan(nxt, w); low[x] = min(low[x], low[nxt]); cut[w] |= low[nxt] > dfn[x]; } else if (w != edge) low[x] = min(low[x], dfn[nxt]); } return; } void dfs(int x) { dcc[x] = cnt; for (auto& y : nbr[x]) { auto& nxt = y.first, w = y.second; if (!cut[w] && !dcc[nxt]) dfs(nxt); } return; } void dfs1(int x, int fa, int& to, int sum = 0) { if (sum >= dis) { to = x; dis = sum; } for (auto& y : new_nbr[x]) { auto& nxt = y.first, w = y.second; if (nxt != fa) dfs1(nxt, x, to, sum + 1); } return; } signed main() { ios::sync_with_stdio(0); cin.tie(0), cout.tie(0); cin >> n >> m; for (int i = 1; i <= m; i++) { int x, y; cin >> x >> y; nbr[x].push_back({ y,i }); nbr[y].push_back({ x,i }); } for (int i = 1; i <= n; i++) if (!dfn[i]) root = i, tarjan(i, 0); for (int i = 1; i <= n; i++) if (!dcc[i]) cnt++, dfs(i); for (int i = 1; i <= n; i++) for (auto& y : nbr[i]) { auto& nxt = y.first, w = y.second; if (dcc[i] != dcc[nxt]) new_nbr[dcc[i]].push_back({ dcc[nxt],w }); } int x = 0, y = 0; dfs1(1, 0, x); dis = 0; dfs1(x, 0, y); cout << dis; return 0; }
|