File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #include < vector>
2+ #include < algorithm>
3+
4+ using namespace std ;
5+
6+ class DisjointSet {
7+ private:
8+ vector<int > parent;
9+ vector<int > rank;
10+
11+ public:
12+ DisjointSet (int n) {
13+ parent.resize (n);
14+ rank.resize (n, 0 );
15+ for (int i = 0 ; i < n; i++) {
16+ parent[i] = i;
17+ }
18+ }
19+
20+ int find (int x) {
21+ if (parent[x] != x) {
22+ parent[x] = find (parent[x]);
23+ }
24+ return parent[x];
25+ }
26+
27+ void unionSet (int x, int y) {
28+ int rootX = find (x);
29+ int rootY = find (y);
30+
31+ if (rootX == rootY) return ;
32+
33+ if (rank[rootX] < rank[rootY]) {
34+ parent[rootX] = rootY;
35+ } else {
36+ parent[rootY] = rootX;
37+ if (rank[rootX] == rank[rootY]) {
38+ rank[rootX]++;
39+ }
40+ }
41+ }
42+ };
43+
44+ int solution (int n, vector<vector<int >> costs) {
45+ // 비용 기준으로 정렬
46+ sort (costs.begin (), costs.end (), [](const vector<int >& a, const vector<int >& b) {
47+ return a[2 ] < b[2 ];
48+ });
49+
50+ DisjointSet ds (n);
51+ int totalCost = 0 ;
52+
53+ for (const auto & cost : costs) {
54+ int from = cost[0 ];
55+ int to = cost[1 ];
56+ int weight = cost[2 ];
57+
58+ if (ds.find (from) != ds.find (to)) {
59+ ds.unionSet (from, to);
60+ totalCost += weight;
61+ }
62+ }
63+
64+ return totalCost;
65+ }
You can’t perform that action at this time.
0 commit comments