-
Notifications
You must be signed in to change notification settings - Fork 0
/
11724.cpp
59 lines (55 loc) · 1.13 KB
/
11724.cpp
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
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Graph{
public:
int N;
vector<vector<int>>adj;
vector<bool>visited;
Graph():N(0){}
Graph(int n):N(n){
adj.resize(N);
visited.resize(N);
}
void addEdge(int u, int v){
adj[u].push_back(v);
adj[v].push_back(u);
}
void sortList(){
for(int i = 0 ; i < N ; i++) {
sort(adj[i].begin(), adj[i].end());
}
}
int dfs(){
int totalElement = 0;
fill(visited.begin(),visited.end(), false);
for(int i = 1 ; i < N ; i++){
if(!visited[i]){
dfs(i);
totalElement++;
}
}
return totalElement;
}
private:
void dfs(int curr){
visited[curr] = true;
for(int next : adj[curr]){
if(!visited[next])
dfs(next);
}
}
};
int main(){
int n, m = 0;
cin >> n >> m;
Graph g(n+1);
for(int i = 0 ; i < m ; i++){
int x, y;
cin >> x >> y;
g.addEdge(x,y);
}
g.sortList();
cout << g.dfs() << endl;
}