Skip to content

Commit 09a2e90

Browse files
authored
Create connecting-cities-with-minimum-cost.cpp
1 parent 00eb45d commit 09a2e90

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
// Time: O(nlogn)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
int minimumCost(int N, vector<vector<int>>& connections) {
7+
sort(connections.begin(), connections.end(),
8+
[](const auto& a, const auto& b) {
9+
return a[2] < b[2];
10+
});
11+
UnionFind union_find(N);
12+
int result = 0;
13+
for (const auto& c : connections) {
14+
if (union_find.union_set(c[0] - 1, c[1] - 1)) {
15+
result += c[2];
16+
}
17+
}
18+
return union_find.size() == 1 ? result : -1;
19+
}
20+
21+
private:
22+
class UnionFind {
23+
public:
24+
UnionFind(const int n) : set_(n), count_(n) {
25+
iota(set_.begin(), set_.end(), 0);
26+
}
27+
28+
int find_set(const int x) {
29+
if (set_[x] != x) {
30+
set_[x] = find_set(set_[x]); // Path compression.
31+
}
32+
return set_[x];
33+
}
34+
35+
bool union_set(const int x, const int y) {
36+
int x_root = find_set(x), y_root = find_set(y);
37+
if (x_root == y_root) {
38+
return false;
39+
}
40+
set_[min(x_root, y_root)] = max(x_root, y_root);
41+
--count_;
42+
return true;
43+
}
44+
45+
int size() const {
46+
return count_;
47+
}
48+
49+
private:
50+
vector<int> set_;
51+
int count_;
52+
};
53+
};

0 commit comments

Comments
 (0)