-
Notifications
You must be signed in to change notification settings - Fork 1
/
JourneyMoon.cpp
75 lines (58 loc) · 1.07 KB
/
JourneyMoon.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
// problem: "https://www.hackerrank.com/challenges/journey-to-the-moon/problem"
#include<iostream>
#include<vector>
#include<queue>
#define ll long long unsigned int
using namespace std;
ll BFS (vector<int>G[],vector<bool>&V,int i)
{
queue<int>Q;
ll c = 1;
Q.push(i);
while(!Q.empty())
{
int j = Q.front();
Q.pop();
int k;
for(k=0;k!=G[j].size();k++)
{
if(V[G[j][k]]==0)
{
V[G[j][k]] = 1;
Q.push(G[j][k]);
c++;
}
}
}
return c;
}
int main()
{
int n,p;
cin>>n>>p;
int x,y;
vector<int>G[n];
while(p--)
{
cin>>x>>y;
G[x].push_back(y);
G[y].push_back(x);
}
vector<bool>V(n,0);
int i;
ll c,s;
c = s = 0;
for(i=0;i!=n;i++)
{
if(V[i]==0)
{
V[i] = 1;
x = BFS(G, V, i); // define function
c += s * x;
s += x;
//cout<<x<<' ';
}
}
cout<<c;
return 0;
}