728x90
반응형
https://www.acmicpc.net/problem/4386
4386번: 별자리 만들기
도현이는 우주의 신이다. 이제 도현이는 아무렇게나 널브러져 있는 n개의 별들을 이어서 별자리를 하나 만들 것이다. 별자리의 조건은 다음과 같다. 별자리를 이루는 선은 서로 다른 두 별을 일
www.acmicpc.net
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
int n;
int parent[101];
vector<pair<double, double>> star;
vector<pair<double, pair<int, int>>> v;
int getParent(int a){
if(a == parent[a]) return a;
return getParent(parent[a]);
}
void unionParent(int a, int b){
a = getParent(a);
b = getParent(b);
parent[b] = a;
}
bool findParent(int a, int b){
a = getParent(a);
b = getParent(b);
if(a == b) return true;
else return false;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout << fixed;
cout.precision(2);
cin >> n;
for(int i = 0; i < n; i++){
double a, b;
cin >> a >> b;
star.push_back({a, b});
}
for(int i = 0; i < n; i++){
double a = star[i].first;
double b = star[i].second;
for(int j = i + 1; j < n; j++){
double aa = star[j].first;
double bb = star[j].second;
double t = sqrt((aa - a) * (aa - a) + (bb - b) * (bb - b));
v.push_back({t, {i, j}});
}
}
sort(v.begin(), v.end());
for(int i = 0; i < n; i++)
parent[i] = i;
double answer = 0;
for(int i = 0; i < v.size(); i++){
if(!findParent(v[i].second.first, v[i].second.second)){
answer += v[i].first;
unionParent(v[i].second.first, v[i].second.second);
}
}
cout << answer << endl;
return 0;
}
간선이 주어지지 않고 정점들의 좌표가 주어졌으므로 모든 정점간의 간선을 만들어 저장하고 크루스칼 알고리즘을 사용하여 해결한다.
728x90
반응형
'Algorithm > BAEKJOON' 카테고리의 다른 글
[BOJ] 1199번 오일러 회로 (C++) (0) | 2022.05.28 |
---|---|
[BOJ] 2150번 Strongly Connected Component (C++) (0) | 2022.05.26 |
[BOJ] 2468번 안전 영역 (C++) (0) | 2022.05.25 |
[BOJ] 20040번 사이클 게임 (C++) (0) | 2022.05.23 |
[BOJ] 1197번 최소 스패닝 트리 (C++) (0) | 2022.05.23 |