BOJ[백준] - 4386 - 별자리 만들기
https://www.acmicpc.net/problem/4386
MST(최소신장트리) 문제네요~ Kruskal (크루스칼) 알고리즘 사용했습니다.
(1) 다만, 이 문제는 직접 edge를 만들어 줘야 하는 번거로움이 있네요.. 피타고라스의 정리를 사용해야 했습니다. ㅎㅎ
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 |
// Kruskal algorithm
#include <cstdio>
#include <math.h>
#include <algorithm>
using namespace std;
typedef struct star
{
double x, y;
} STAR;
typedef struct edge
{
int a, b;
double w;
} EDGE;
const int MXN = 100, MXM = 10000;
EDGE e[MXM + 1], tmp[MXM + 1];
int rep[MXN + 1]; // parent vertex info
STAR st[101];
int f(int x) // return representative vertex's index
{
if(x == rep[x])
return x;
else
return (rep[x] = f(rep[x]));
}
void mergesort(int l, int r)
{
if(l < r)
{
int m = (l + r) / 2;
mergesort(l, m);
mergesort(m + 1, r);
// p1 [l ~ m], p2 [m+1 ~ r], p3 [l ~ r]
int p1 = l, p2 = m + 1, p3 = l;
while(p1 <= m && p2 <= r)
{
if(e[p1].w < e[p2].w) // judgement factor is weight(cost)
tmp[p3++] = e[p1++];
else
tmp[p3++] = e[p2++];
}
while(p1 <= m) tmp[p3++] = e[p1++];
while(p2 <= r) tmp[p3++] = e[p2++];
for(int i = l; i <= r; i++)
e[i] = tmp[i];
}
}
int main()
{
int n;
scanf("%d", &n);
for(int i = 0; i < n; i++)
scanf("%lf %lf", &st[i].x, &st[i].y);
int ne = 0; // number of edges
for(int i = 0; i < n; i++)
{
for(int j = i + 1; j < n; j++)
{
e[ne].a = i;
e[ne].b = j;
e[ne].w = sqrt(pow(abs(st[i].x - st[j].x), 2) + pow(abs(st[i].y - st[j].y), 2));
ne++;
}
}
for(int i = 0; i <= ne; i++)
rep[i] = i;
mergesort(0, ne - 1);
// scan the all of original edge data,
// BUT if the # of edges will be ( n-1 ), that's the Minimum Spanning Tree
// because all the vertices are connected.
int cnt = 0;
double ans = 0;
for(int i = 0; i < ne; i++)
{
int r1 = f(e[i].a), r2 = f(e[i].b);
if(r1 == r2) // a and b are in the same union
continue;
rep[r2] = r1;
ans += e[i].w;
cnt++;
if(cnt == n - 1)
break;
}
printf("%.2lf", ans);
return 0;
} |
cs |
'Algorithm 문제풀이 > BOJ [백준] 문제풀이' 카테고리의 다른 글
BOJ[백준] - 1126 - 같은탑 (0) | 2017.07.15 |
---|---|
BOJ[백준] - 6497 - 전력난 (0) | 2017.07.14 |
BOJ[백준] - 1922 - 네트워크 연결 (0) | 2017.07.14 |
BOJ[백준] - 1647 - 도시 분할 계획 (0) | 2017.07.14 |
BOJ[백준] - 2610 - 회의준비 (0) | 2017.07.14 |