Algorithm/Baekjoon
[Algorithm]Baekjoon 4386 :: 별자리 만들기
MaxLevel
2024. 2. 22. 18:15
https://www.acmicpc.net/problem/4386
4386번: 별자리 만들기
도현이는 우주의 신이다. 이제 도현이는 아무렇게나 널브러져 있는 n개의 별들을 이어서 별자리를 하나 만들 것이다. 별자리의 조건은 다음과 같다. 별자리를 이루는 선은 서로 다른 두 별을 일
www.acmicpc.net
|
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
|
using namespace std;
struct Node
{
float distance;
int node1;
int node2;
};
bool cmp(const Node& a, const Node& b)
{
return a.distance < b.distance;
}
int parents[100001] = { 0 };
int findParent(int node)
{
if (node == parents[node]) return node;
return parents[node] = findParent(parents[node]);
}
void unionParents(int a, int b)
{
a = findParent(a);
b = findParent(b);
if (a < b) parents[b] = a;
else parents[a] = b;
}
bool isSameParents(int a, int b)
{
a = findParent(a);
b = findParent(b);
if (a == b) return true;
return false;
}
int n;
vector<pair<float, float>> positions;
vector<Node> nodes;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
for (int i = 0; i < n; ++i)
{
parents[i] = i;
}
for (int i = 0; i < n; ++i)
{
float x, y;
cin >> x >> y;
positions.push_back({ x, y });
}
for (int i = 0; i < n; ++i)
{
for (int j = i + 1; j < n; ++j)
{
float xGap = powf(positions[i].first - positions[j].first, 2);
float yGap = powf(positions[i].second - positions[j].second, 2);
float distance = sqrt(xGap + yGap);
nodes.push_back({ distance,i,j });
}
}
sort(nodes.begin(), nodes.end(), cmp);
float answer = 0.0f;
for (int i = 0; i < nodes.size(); ++i)
{
if (isSameParents(nodes[i].node1, nodes[i].node2) == false)
{
unionParents(nodes[i].node1, nodes[i].node2);
answer += nodes[i].distance;
}
}
printf("%.2f", answer);
}
|
cs |
전형적인 MST문제. 소수점 둘째자리수까지만 출력해줘야 하는것을 잊지말자.