-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathJourneyToTheMoon.cpp
48 lines (45 loc) · 977 Bytes
/
JourneyToTheMoon.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
#include <iostream>
#include <algorithm>
#include <set>
#include <queue>
#include <vector>
using namespace std;
int N,K,A,B,C[100000] ;
vector<int> G[100000];
queue<int> Q;
vector<int>::iterator it;
long long colour(int root) {
C[root] = 1;
Q.push(root);
long long result = 1;
while(!Q.empty()) {
int u = Q.front();
Q.pop();
for(it = G[u].begin(); it != G[u].end(); it++) {
int v = *it;
if(C[v]==0) {
C[v] = 1;
result++;
Q.push(v);
}
}
}
return result;
}
int main() {
cin >> N >> K;
for(int i = 0; i < K; i++) {
cin >> A >> B;
G[A].push_back(B);
G[B].push_back(A);
}
long long result = 0;
long long sum = 0;
for(int i = 0; i < N; i++)
if(C[i]==0) {
long long x = colour(i);
result += sum*x;
sum += x;
}
cout << result << endl;
}