-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfind_unrelated_friends.cpp
56 lines (45 loc) · 1000 Bytes
/
find_unrelated_friends.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
// Find number of possible combinations of unrelated friends group of 2 people
// from the given graph
// Using connected component approach
#include<bits/stdc++.h>
using namespace std;
vector<bool> visited;
int n, m;
vector<vector<int>> adj;
vector<int> components;
int getComp(int idx) {
if(visited[idx]) {
return 0;
}
visited[idx] = true;
int ans = 1;
for(auto i: adj[idx]) {
if(!visited[i]) {
ans += getComp(i);
visited[i] = true;
}
}
return ans;
}
int main() {
cin>>n>>m;
adj = vector<vector<int>>(n);
visited = vector<bool>(n);
for(int i=0; i<m; i++) {
int u, v;
cin>>u>>v;
adj[u].push_back(v);
adj[v].push_back(u);
}
for(int i=0; i<n; i++) {
if(!visited[i]) {
components.push_back(getComp(i));
}
}
int ans = 0;
for(auto i: components) {
ans += i*(n-i);
}
cout<<ans/2<<endl;
return 0;
}