This repository was archived by the owner on Jan 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathjourney_moon.cpp
More file actions
81 lines (61 loc) · 1.6 KB
/
journey_moon.cpp
File metadata and controls
81 lines (61 loc) · 1.6 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// https://www.hackerrank.com/challenges/journey-to-the-moon
#include <iostream>
#include <map>
#include <vector>
using namespace std;
class UnionFind {
private:
vector<int> p;
vector<int> rank;
public:
UnionFind(int N) {
p.assign(N, 0);
rank.assign(N, 0);
for (int i = 0; i < N; i++)
p[i] = i;
}
int findSet(int i) {
return (p[i] == i ? i : (p[i] = findSet(p[i])));
}
bool isSameSet(int i, int j) {
return findSet(i) == findSet(j);
}
void unionSet(int i, int j) {
if (!isSameSet(i, j)) {
int x = findSet(i);
int y = findSet(j);
if (rank[x] > rank[y])
p[y] = x;
else {
p[x] = y;
if (rank[x] == rank[y])
rank[y]++;
}
}
}
};
long long getNumberOfWaysToPair(int N, vector<pair<int, int> > sameCountry) {
int I = sameCountry.size();
UnionFind uf(N);
for (int i = 0; i < I; i++)
uf.unionSet(sameCountry[i].first, sameCountry[i].second);
map<int, int> countryCount;
for (int i = 0; i < N; i++)
countryCount[uf.findSet(i)]++;
long long total = 0;
for (int i = 0; i < N; i++)
total += N - countryCount[uf.findSet(i)];
return total / 2;
}
int main() {
int N, I;
vector<pair<int, int> > sameCountry;
cin >> N >> I;
for (int i = 0; i < I; i++) {
pair<int, int> p;
cin >> p.first >> p.second;
sameCountry.push_back(p);
}
cout << getNumberOfWaysToPair(N, sameCountry) << endl;
return 0;
}