[Hacker Rank] Roads and Libraries

Roads and Libraries

  • Time : O(clogn)
  • 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
23
24
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 roadsAndLibraries(long long n, long long lib, long long road, vector<vector<int>> cities) {
if(lib <= road) return lib * n;
for(int i = 1; i <= n; i++) uf[i] = i;
long long res = 0;
for(auto& c : cities) {
int u = c[0], v = c[1];
if(find(u) != find(v)) {
uni(u, v);
res += road;
}
}
unordered_set<int> us;
for(int i = 1; i <= n; i++) us.insert(find(i));
return res + us.size() * lib;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/08/PS/HackerRank/torque-and-development/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.