A network has n computers and m cables. Computers joined by a chain of cables are in the same group. Count the groups.
What to build
Store the cables in an adjacency list. Loop over the computers; every time you meet one that has not been seen, add 1 to the answer and run DFS from it to mark its whole group.
Requirements
- Use DFS and a
seenarray - A computer with no cable is a group of its own
Input
The first line has n and m. Each of the next m lines has two computers a b (1-based).
Output
The number of groups.
Constraints
1 ≤ n ≤ 10,000. 0 ≤ m ≤ 20,000. Pairs may repeat.
Example
Input:
6 4
1 2
2 3
4 5
5 4
Output:
3
Why it works
DFS from one computer marks every computer reachable from it, which is exactly its group. Each new start therefore belongs to a group not counted before, so the number of starts is the number of groups.
Examples
6 4 1 2 2 3 4 5 5 4
3
3 0
3
Hints
Hint 1
vector<vector<int>> adj(n + 1); vector<bool> seen(n + 1, false); make them global.
Hint 2
void dfs(int u) { seen[u] = true; for (int v : adj[u]) if (!seen[v]) dfs(v); }
Hint 3
The recursion goes at most 10,000 deep, which is fine.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int> > adj;
vector<bool> seen;
void dfs(int u) {
seen[u] = true;
for (int v : adj[u])
if (!seen[v]) dfs(v);
}
int main() {
int n, m;
cin >> n >> m;
adj.assign(n + 1, vector<int>());
seen.assign(n + 1, false);
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
int groups = 0;
for (int u = 1; u <= n; u++) {
if (!seen[u]) {
groups++;
dfs(u);
}
}
cout << groups << "\n";
return 0;
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step