-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberOfOperationsToMakeNetConnectied.cpp
More file actions
40 lines (37 loc) · 1.05 KB
/
Copy pathNumberOfOperationsToMakeNetConnectied.cpp
File metadata and controls
40 lines (37 loc) · 1.05 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
#include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize ("-O3")
class Solution {
public:
int find(vector<int>&v, int x){
if(v[x]==x)return x;
return find(v, v[x]) ;
}
void uniong(vector<int>&v, int x, int y){
int fx=find(v, x); int fy=find(v, y);
if(fx==fy)cnt++; // cnt == total redundant edges that makes cycle in graph
if(fx>fy)
v[fx]=fy;
else{
v[fy]=fx ;
}
}
int cnt;
int makeConnected(int key, vector<vector<int>>& con) {
int n=con.size(); if(n<key-1)return -1; //atleast n-1 edges to make a graph of n nodes connected
cnt=0;
vector<int> v(key, 0); for(int i=0;i<key;i++) v[i]=i ;
for(int i=0; i<n; i++){
uniong(v, con[i][0], con[i][1]) ;
}
int con_so_far=n-cnt+1; int cnt_left=key-con_so_far;
if(cnt_left<=cnt)return cnt_left ;
else
return -1;
}
};
int main(){
ios_base::sync_with_stdio(0);
cin.tie(NULL); cout.tie(NULL);
return 0;
}