-
Notifications
You must be signed in to change notification settings - Fork 0
/
connecting_the_graphs.cpp
102 lines (93 loc) · 2.3 KB
/
connecting_the_graphs.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
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
94
95
96
97
98
99
100
101
102
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
class DisjointSet {
vector<int> rank, parent, size;
public:
DisjointSet(int n) {
rank.resize(n + 1, 0);
parent.resize(n + 1);
size.resize(n + 1);
for (int i = 0; i <= n; i++) {
parent[i] = i;
size[i] = 1;
}
}
int findUPar(int node) {
if (node == parent[node])
return node;
return parent[node] = findUPar(parent[node]);
}
void unionByRank(int u, int v) {
int ulp_u = findUPar(u);
int ulp_v = findUPar(v);
if (ulp_u == ulp_v) return;
if (rank[ulp_u] < rank[ulp_v]) {
parent[ulp_u] = ulp_v;
}
else if (rank[ulp_v] < rank[ulp_u]) {
parent[ulp_v] = ulp_u;
}
else {
parent[ulp_v] = ulp_u;
rank[ulp_u]++;
}
}
void unionBySize(int u, int v) {
int ulp_u = findUPar(u);
int ulp_v = findUPar(v);
if (ulp_u == ulp_v) return;
if (size[ulp_u] < size[ulp_v]) {
parent[ulp_u] = ulp_v;
size[ulp_v] += size[ulp_u];
}
else {
parent[ulp_v] = ulp_u;
size[ulp_u] += size[ulp_v];
}
}
};
class Solution {
public:
int Solve(int n, vector<vector<int>>& edge) {
DisjointSet ds(n);
int cntExtra=0;
for(auto it:edge){
int u=it[0];
int v=it[1];
if(ds.findUPar(u)==ds.findUPar(v))cntExtra++;
else ds.unionBySize(u,v);
}
int connected=0;
for(int i=0;i<n;i++){
if(ds.findUPar(i)==i)connected++;
}
if(cntExtra>=connected-1)return connected-1;
else return -1;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int n, m;
cin >> n >> m;
vector<vector<int>> adj;
for (int i = 0; i < m; ++i) {
vector<int> temp;
for (int j = 0; j < 2; ++j) {
int x;
cin >> x;
temp.push_back(x);
}
adj.push_back(temp);
}
Solution Obj;
cout << Obj.Solve(n, adj) << "\n";
}
return 0;
}
// } Driver Code Ends