4386번: 별자리 만들기
도현이는 우주의 신이다. 이제 도현이는 아무렇게나 널브러져 있는 n개의 별들을 이어서 별자리를 하나 만들 것이다. 별자리의 조건은 다음과 같다. 별자리를 이루는 선은 서로 다른 두 별을 일
www.acmicpc.net
문제에서 가중치는 주어지지 않는다. 따라서 우리가 직접 가중치값을 설정해줘야 하는데
각 별의 위치를 받으면 \(O(N^2)\)으로 가중치를 쉽게 설정해줄 수 있다.
거리 공식은 \(\sqrt{(x_1-x_2)^2 + (y_1-y_2)^2}\) 이다.
#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
struct P {
int u, v;
double w;
};
vector<P> ar;
vector<pair<double, double>> d;
vector<int> uf;
int n, cnt;
double ans;
int find(double x) {
return uf[x] < 0 ? x : uf[x] = find(uf[x]);
}
bool merge(double x, double y) {
x = find(x);
y = find(y);
if (x == y) return false;
uf[y] = x;
return true;
}
double cal(double x1, double y1, double x2, double y2) {
return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}
int main() {
ios::sync_with_stdio(false); cin.tie(0);
cin >> n;
uf.resize(n + 1, -1);
d.resize(n);
for (int i = 0; i < n; ++i) cin >> d[i].first >> d[i].second;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < i; ++j) {
double dist = cal(d[i].first, d[i].second, d[j].first, d[j].second);
ar.push_back({ j,i,dist });
}
}
sort(ar.begin(), ar.end(), [](const P& a, const P& b) { return a.w < b.w; });
for (int i = 0;; ++i) {
if (merge(ar[i].u, ar[i].v)) {
ans += ar[i].w;
if (++cnt == n - 1) break;
}
}
cout << ans << endl;
return 0;
}
'알고리즘 > BOJ' 카테고리의 다른 글
BOJ 11048 이동하기 (0) | 2020.11.20 |
---|---|
BOJ 인내의 도미노 장인 호석 (0) | 2020.11.19 |
BOJ 1922 네트워크 연결 (0) | 2020.11.14 |
BOJ 10282 해킹 (0) | 2020.11.11 |
BOJ 2573 빙산 (0) | 2020.11.07 |