티스토리 뷰
문제 출처: https://www.acmicpc.net/problem/4386
4386번: 별자리 만들기
도현이는 우주의 신이다. 이제 도현이는 아무렇게나 널브러져 있는 n개의 별들을 이어서 별자리를 하나 만들 것이다. 별자리의 조건은 다음과 같다. 별자리를 이루는 선은 서로 다른 두 별을 일
www.acmicpc.net
좌표들을 받아서 두 점 사이의 거리를 계산 한 뒤 MST로 구할 수 있다.
#include<iostream>
#include<algorithm>
#include<math.h>
#include<cstring>
using namespace std;
struct P {
int a, b;
double dist;
};
bool cmp(P a, P b) {
return a.dist < b.dist;
}
double dist(double x1, double y1, double x2, double y2) {
return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}
int u[101];
int find(int a) {
if (u[a] < 0)return a;
return u[a] = find(u[a]);
}
void merge(int a, int b) {
a = find(a);
b = find(b);
if (a == b)return;
if (u[a] < u[b]) {
u[a] += u[b];
u[b] = a;
}
else {
u[b] += u[a];
u[a] = b;
}
}
int main(void)
{
ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
int n; cin >> n;
double pos[101][2];
P arr[10001];
memset(u, -1, sizeof(u));
for (int i = 0; i < n; i++) {
cin >> pos[i][0] >> pos[i][1];
}
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j)continue;
double val = dist(pos[i][0], pos[i][1], pos[j][0], pos[j][1]);
arr[count] = { i,j,val };
count++;
}
}
sort(arr, arr+count, cmp);
double sum = 0;
for (int i = 0; i < count; i++) {
P curr = arr[i];
if (find(curr.a) == find(curr.b))continue;
else {
merge(curr.a, curr.b);
sum += curr.dist;
}
}
printf("%0.2lf", sum);
}'PS' 카테고리의 다른 글
| [백준] 9322번 철벽 보안 알고리즘 C++ (0) | 2022.07.13 |
|---|---|
| [백준] 14402번 야근 C++ (0) | 2022.07.12 |
| [백준] 1495번 기타리스트 C++ (0) | 2022.07.11 |
| [백준] 2001번 보석 줍기 C++ (0) | 2022.07.10 |
| [백준] 1194번 달이 차오른다, 가자. C++ (0) | 2022.07.09 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 후위 표기식
- 백준
- 1918
- 스택
- 벨만포드
- C++
- 11657
- 6539
- 골목길C++
- 소셜네트워킹어플리케이션
- 1738
- 7511
- 중위 표기식 후위 표기식으로 변환
- 벨만-포드
- tea time
- 6018
- 어린왕자 C++
- 타임머신
- 상범빌딩
- 1004
- 골목길
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 |
글 보관함
