FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
Data-Structures-Algorithms/Graphs/DSU.cpp at master · Arhantcode1/Data-Structures-Algorithms · GitHub
Arhantcode1
/
Data-Structures-Algorithms
Public
forked from
CodersForLife/Data-Structures-Algorithms
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
Data-Structures-Algorithms
/
Graphs
/
DSU.cpp
Copy path
More file actions
More file actions
Latest commit
History
History
History
47 lines (45 loc) · 1.29 KB
Breadcrumbs
Data-Structures-Algorithms
/
Graphs
/
DSU.cpp
Copy path
File metadata and controls
47 lines (45 loc) · 1.29 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
#
include
<
stdio.h
>
#
include
<
vector
>
using
namespace
std
;
int
find
(
int
* parent,
int
val) {
if
(parent[val]!=val)
parent[val]=
find
(parent,parent[val]);
//
find the leader of the group of this node
return
parent[val];
}
void
unionSet
(
int
* parent,
int
a,
int
b) {
int
ap =
find
(parent,a);
int
bp =
find
(parent,b);
if
(ap!=bp)
parent[bp]=ap;
//
make 'a's parent as the leader of b's group as well.
}
int
countNumberOfComponents
(vector<vector<
int
>>& M) {
int
n = M.
size
();
int
parent[n];
//
stores parent for each node
for
(
int
i=
0
;i<n;i++) parent[i]=i;
//
initially every node is individual
for
(
int
i=
0
;i<n;i++) {
for
(
int
j=i+
1
;j<n;j++) {
if
(M[i][j] && parent[i]!=parent[j]) {
unionSet
(parent,i,j);
//
if there is an edge, but parents are different that means these
//
two nodes(and hence the tress asociated with them) can be clubbed
}
}
}
//
this now counts number of components.
int
count=
0
;
for
(
int
i=
0
;i<n;i++) {
if
(parent[i]==i) count++;
}
return
count;
}
int
main
() {
int
vertices,edges,from,to;
scanf
(
"
%d%d
"
,&vertices,&edges);
vector<vector<
int
> >
adjacencyMatrix
(vertices, vector<
int
>(vertices,
0
));
for
(
int
i=
0
;i<edges;i++)
{
scanf
(
"
%d%d
"
,&from,&to);
adjacencyMatrix[from][to]=adjacencyMatrix[to][from]=
1
;
}
printf
(
"
%d
"
,
countNumberOfComponents
(adjacencyMatrix));
return
0
;
}
Back
|
FazBrowse Home
|
New Git URL