forked from vineetyadav2403/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Journey to the Moon.cpp
45 lines (43 loc) · 937 Bytes
/
Journey to the Moon.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
//https://www.hackerrank.com/challenges/journey-to-the-moon/problem?isFullScreen=true
#include <bits/stdc++.h>
using namespace std;
int n,p;
void dfs(vector<int> a[],vector<bool> &visited, int i, set<int> &s){
if(!visited[i]){
visited[i] = true;
s.insert(i);
for(auto x: a[i]){
dfs(a,visited,x,s);
}
}
}
int main()
{
cin>>n>>p;
vector<int> a[n];
vector<bool> visited(n,false);
set<int> s;
s.clear();
vector<int> comp;
for(int i=0 ;i<p;i++){
int x, y;
cin>>x>>y;
a[x].push_back(y);
a[y].push_back(x);
}
for(int i=0;i<n;i++){
dfs(a,visited,i,s);
if(s.size())
comp.push_back(s.size());
s.clear();
}
long long sum = 0;
long long result = 0;
for(int size : comp)
{
result += sum*size;
sum += size;
}
cout<<result<<endl;
return 0;
}