-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathE_Non_academic_Problem.cpp
More file actions
93 lines (84 loc) · 2.48 KB
/
E_Non_academic_Problem.cpp
File metadata and controls
93 lines (84 loc) · 2.48 KB
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
84
85
86
87
88
89
90
91
92
93
#include <iostream>
#include <vector>
#include <algorithm>
#include <limits>
#define int long long
using namespace std;
int n, m;
vector<vector<int>> adj;
vector<int> levels, topmostlevelreachable, subtree_size;
vector<bool> visited;
vector<pair<int,int>> bridges;
int t_case = 0;
void dfs(int node, int parent, int level) {
visited[node] = true;
levels[node] = level;
topmostlevelreachable[node] = level;
subtree_size[node] = 1;
for (int nb : adj[node]) {
if (nb == parent) continue;
if (!visited[nb]) {
dfs(nb, node, level + 1);
// after returning, we know subtree_size[nb]
subtree_size[node] += subtree_size[nb];
topmostlevelreachable[node] = min(topmostlevelreachable[node], topmostlevelreachable[nb]);
if (topmostlevelreachable[nb] > level) {
// (node, nb) is a bridge
bridges.emplace_back(node, nb);
}
} else {
// back‐edge
topmostlevelreachable[node] = min(topmostlevelreachable[node], levels[nb]);
}
}
}
void solve() {
cin >> n >> m;
adj.assign(n+1, {});
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
levels.assign(n+1, 0);
topmostlevelreachable.assign(n+1, numeric_limits<int>::max());
visited.assign(n+1, false);
subtree_size.assign(n+1, 0);
bridges.clear();
// run our bridge‐finding DFS
dfs(1, -1, 0);
// total possible pairs
int total_pairs = n * (n - 1) / 2;
// if no bridges, removing any edge keeps it connected
if (bridges.empty()) {
cout << total_pairs << "\n";
} else {
// find the bridge whose removal maximizes subtree_size * (n - subtree_size)
int best_unreach = 0;
pair<int,int> best_edge = { -1, -1 };
for (auto [u,v] : bridges) {
// ensure v is the child in the DFS tree
if (levels[u] > levels[v]) swap(u,v);
int s = subtree_size[v];
int unreach = s * (n - s);
if (unreach > best_unreach) {
best_unreach = unreach;
best_edge = {u, v};
}
}
int min_reachable = total_pairs - best_unreach;
cout << min_reachable << "\n";
}
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
int T;
cin >> T;
while (T--) {
t_case++;
solve();
}
return 0;
}