Game Develop

[Algorithm]Baekjoon 6497번 :: 전력난 본문

Algorithm/Baekjoon

[Algorithm]Baekjoon 6497번 :: 전력난

MaxLevel 2025. 3. 19. 08:36

https://www.acmicpc.net/problem/6497

 

 

 

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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
#include <math.h>
#include <queue>
#include <functional>
#include <sstream>
#include <memory.h>
#include <deque>
#include <set>
#include <unordered_map>
#include <stack>
#include <numeric>
#include <climits>
#include <bitset>
#include <cmath>
#include <mutex>
 
using namespace std;
 
 
struct Node
{
    int x, y, z;
};
 
bool cmp(const Node& a, const Node& b)
{
    return a.z < b.z;
}
 
int m, n, x, y, z;
int parents[2000001= { 0 };
 
 
int GetParents(int node)
{
    if (node == parents[node])
    {
        return node;
    }
 
    return parents[node] = GetParents(parents[node]);
}
 
void UnionParents(int node1, int node2)
{
    int node1Parent = GetParents(node1);
    int node2Parent = GetParents(node2);
 
    if (node1Parent < node2Parent)
    {
        parents[node2Parent] = node1Parent;
    }
    else
    {
        parents[node1Parent] = node2Parent;
    }
}
 
bool IsSameParents(int node1, int node2)
{
    return GetParents(node1) == GetParents(node2);
}
 
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
 
    vector<int> answers;
   
    while (1)
    {
        cin >> m >> n;
 
        if (m == 0 && n == 0)
        {
            break;
        }
 
        int sum = 0;
        vector<Node> nodes(n);
 
        for (int i = 0; i < m; ++i)
        {
            parents[i] = i;
        }
 
        for (int i = 0; i < n; ++i)
        {
            cin >> nodes[i].x >> nodes[i].y >> nodes[i].z; 
        }
 
        sort(nodes.begin(), nodes.end(), cmp);
 
        for (int i = 0; i < n; ++i)
        {
            if (!IsSameParents(nodes[i].x, nodes[i].y))
            {
                UnionParents(nodes[i].x, nodes[i].y);
            }
            else
            {
                sum += nodes[i].z;
            }
        }
 
        answers.push_back(sum);
    }
   
    for (int i = 0; i < answers.size(); ++i)
    {
        cout << answers[i] << endl;
    }
 
    return 0;
}
 
 
 
 
 
cs

 

무난한 MST문제이다. 알고리즘 오랜만에 풀어도 UnionParent로 하는 MST는 손에 익어서 그런가, 쉽게쉽게 작성된다.

 

그나마 한가지 유의할 점은, 문제에서의 답은 '아낀 돈'이다. MST를 만드는데 사용된 돈이 아니라, 아낀 돈이니까 합칠때 말고 그냥 넘어갈 때 sum값에 누적시켜주면 된다.