-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContest_2.cpp
More file actions
53 lines (44 loc) · 1.12 KB
/
Copy pathContest_2.cpp
File metadata and controls
53 lines (44 loc) · 1.12 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
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
void dfs(int node, vector<vector<int>>& adj, vector<bool>& visited) {
visited[node] = true;
for (int neighbor : adj[node]) {
if (!visited[neighbor]) {
dfs(neighbor, adj, visited);
}
}
}
int makeConnected(int n, vector<vector<int>>& connections) {
if (connections.size() < n - 1) {
return -1;
}
vector<vector<int>> adj(n);
for (auto& conn : connections) {
adj[conn[0]].push_back(conn[1]);
adj[conn[1]].push_back(conn[0]);
}
vector<bool> visited(n, false);
int components = 0;
for (int i = 0; i < n; i++) {
if (!visited[i]) {
components++;
dfs(i, adj, visited);
}
}
return components - 1;
}
int main() {
int n, m;
cin >> n >> m;
vector<vector<int>> connections;
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
connections.push_back({a, b});
}
int result = makeConnected(n, connections);
cout << result << endl;
return 0;
}