forked from vedant781999/Array_operation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnected-Components-Graphs.cpp
More file actions
65 lines (59 loc) · 1.09 KB
/
Connected-Components-Graphs.cpp
File metadata and controls
65 lines (59 loc) · 1.09 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
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
#include<bits/stdc++.h>
using namespace std;
vector<bool> vis;
int n,m;
vector<vector<int>> adj;
vector<int> components;
int get_comp(int idx)
{
if(vis[idx])
{
return 0;
}
vis[idx]=true;
int ans=1;
for(auto i : adj[idx])
{
if(!vis[i])
{
ans+=get_comp(i);
vis[i]=true;
}
}
return ans;
}
int main()
{
cin>>n>>m;
adj = vector<vector<int>>(n);
vis = vector<bool>(n,0);
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(!vis[i])
{
components.push_back(get_comp(i));
}
}
for(auto i : components)
{
cout<<i<<" ";
}
// choosing friend pair from other group
long long ans=0;
for(auto i : components)
{
ans+=i*(n-i);
}
//overcounting ko hatane ke liye
// 2 3
// 3 2 both are counted so divided by 2
cout<<"\n"<<(ans)/2;
return 0;
}