[Hacker Rank] Journey to the Moon

Journey to the Moon

  • Time : O(alogn)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int uf[100001];
int find(int u) {
return u == uf[u] ? u : uf[u] = find(uf[u]);
}
void uni(int u, int v) {
int pu = find(u), pv = find(v);
uf[pu] = uf[pv] = min(pu, pv);
}
long long journeyToMoon(long long n, vector<vector<int>> astronaut) {
for(int i = 0; i < n; i++) uf[i] = i;
for(auto& a : astronaut) {
int u = a[0], v = a[1];
uni(u, v);
}
unordered_map<int, long long> freq;
for(int i = 0; i < n; i++) freq[find(i)]++;
long long res = 0;
for(auto& [_, f] : freq) {
res += f * (n - f);
}
return res / 2;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/08/PS/HackerRank/journey-to-the-moon/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.