Skip to content

Commit 69bade5

Browse files
Add files via upload
1 parent f6f0995 commit 69bade5

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/**CF2063 C
2+
*
3+
* There are only 2 different cases to consider:
4+
* - If we remove two adjacent nodes
5+
* - If we remove two non-adjacent nodes
6+
*
7+
* If we remove adjacent nodes, the answer is the sum of the degrees of the two nodes minus 2
8+
* If we remove non-adjacent nodes, the answer is the sum of their degees minus 1
9+
*
10+
* We iterate over each such case separately and find the maximum answer
11+
*
12+
* Time: O(n log n), Space: O(n)
13+
*/
14+
#pragma GCC optimize("Ofast")
15+
#pragma GCC optimize("unroll-loops")
16+
#include <bits/stdc++.h>
17+
using namespace std;
18+
19+
typedef long long ll;
20+
int n;
21+
multiset<ll> degs;
22+
int main() {
23+
int tc;
24+
cin >> tc;
25+
while (tc--) {
26+
cin >> n;
27+
vector<pair<int, int>> edges;
28+
vector<vector<int>> adjlist(n, vector<int>());
29+
degs.clear();
30+
31+
vector<ll> vDeg(n, 0);
32+
for (int i = 0; i < n - 1; i++) {
33+
int u, v;
34+
cin >> u >> v;
35+
u--;
36+
v--;
37+
38+
edges.push_back({u, v});
39+
vDeg[u]++;
40+
vDeg[v]++;
41+
adjlist[u].push_back(v);
42+
adjlist[v].push_back(u);
43+
}
44+
45+
for (int i = 0; i < n; i++) {
46+
degs.insert(vDeg[i]);
47+
}
48+
49+
ll ans = 0;
50+
for (auto &[u, v] : edges) {
51+
ans = max(ans, vDeg[u] + vDeg[v] - 2);
52+
}
53+
54+
for (int i = 0; i < n; i++) {
55+
degs.erase(degs.find(vDeg[i]));
56+
for (auto &v : adjlist[i]) {
57+
degs.erase(degs.find(vDeg[v]));
58+
}
59+
60+
if (!degs.empty()) ans = max(ans, vDeg[i] + *degs.rbegin() - 1);
61+
62+
degs.insert(vDeg[i]);
63+
for (auto &v : adjlist[i]) {
64+
degs.insert(vDeg[v]);
65+
}
66+
}
67+
68+
cout << ans << endl;
69+
}
70+
71+
return 0;
72+
}

0 commit comments

Comments
 (0)