File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ ``` cpp
2+ #include < bits/stdc++.h>
3+ using namespace std ;
4+
5+ int N;
6+ vector<vector<int >> v (100001);
7+ int d[ 100001] {}, dd[ 100001] {}, u[ 100001] {};
8+ int ans = 0;
9+
10+ void dfs(int n, int p) {
11+ int mx1 = 0, mx2 = 0, mx3 = 0;
12+ for (int i : v[ n] ) if (i != p) {
13+ dfs(i, n);
14+ int res = d[ i] + 1;
15+ if (res > mx1) mx3 = mx2, mx2 = mx1, mx1 = res;
16+ else if (res > mx2) mx3 = mx2, mx2 = res;
17+ else if (res > mx3) mx3 = res;
18+ }
19+ d[ n] = mx1, dd[ n] = mx2;
20+ if (mx3) ans = max(ans, mx1 + mx2 + mx3 + 1);
21+ }
22+
23+ void dfs2(int n, int p) {
24+ if (n != 1) u[ n] = max(u[ p] , d[ p] == d[ n] + 1 ? dd[ p] : d[ p] ) + 1;
25+ if (u[ n] && dd[ n] ) ans = max(ans, d[ n] + dd[ n] + u[ n] + 1);
26+ for (int i : v[ n] ) if (i != p) dfs2(i, n);
27+ }
28+
29+ int main() {
30+ cin.tie(0)->sync_with_stdio(0);
31+
32+ cin >> N;
33+ for (int i = 1, a, b; i < N; i++) {
34+ cin >> a >> b;
35+ v[a].push_back(b);
36+ v[b].push_back(a);
37+ }
38+ dfs(1, 0);
39+ dfs2(1, 0);
40+ cout << ans;
41+
42+ }
43+ ```
You can’t perform that action at this time.
0 commit comments