-
Notifications
You must be signed in to change notification settings - Fork 2
/
16398_josueyeon.cpp
68 lines (56 loc) · 1.25 KB
/
16398_josueyeon.cpp
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
// MST: 최소 스패닝 트리 - kruskal algorithm
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int parent[1001];
int findParent(int x)
{
return (x == parent[x] ? x : parent[x] = findParent(parent[x]));
}
void unionParent(int a, int b)
{
a = findParent(a);
b = findParent(b);
if (a < b)
parent[b] = a;
else
parent[a] = b;
}
int main()
{
cin.tie(0);
cout.tie(0);
ios::sync_with_stdio(false);
int N;
cin>>N;
vector<pair<int, pair<int, int>>> graph;
fill_n(parent, N + 1, 0);
for(int i = 1;i <= N;i++)
parent[i] = i;
for(int i = 1;i <= N;i++)
{
for(int j = 1;j <= N;j++)
{
int temp;
cin>>temp;
if (j >= i + 1)
graph.push_back({temp, {i, j}});
}
}
sort(graph.begin(), graph.end());
long result = 0;
for(int i = 0;i < graph.size();i++)
{
int x = graph[i].second.first;
int y = graph[i].second.second;
int w = graph[i].first;
if (findParent(x) != findParent(y))
{
result += w;
unionParent(x, y);
}
}
cout<<result<<"\n";
return 0;
}