Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 유니온 파인드
- 투 포인터
- 누적 합
- 수학
- BFS
- 다이나믹 프로그래밍
- 트리
- Unreal Engine 5
- DFS
- 알고리즘
- 정렬
- 백준
- 그래프
- ue5
- Team Fortress 2
- 자료구조
- VR
- 시뮬레이션
- 다익스트라
- 구현
- 스택
- c++
- 브루트포스
- XR Interaction Toolkit
- 백트래킹
- 우선순위 큐
- 그리디 알고리즘
- 문자열
- 유니티
- 재귀
Archives
- Today
- Total
1일1알
백준 1774번 우주신과의 교감 C++ 본문
https://www.acmicpc.net/problem/1774
1774번: 우주신과의 교감
(1,1) (3,1) (2,3) (4,3) 이렇게 우주신들과 황선자씨의 좌표가 주어졌고 1번하고 4번이 연결되어 있다. 그렇다면 1번하고 2번을 잇는 통로를 만들고 3번하고 4번을 잇는 통로를 만들면 신들과 선자씨끼
www.acmicpc.net
유니온 파인드 자료구조를 이용해서 최소 스패닝 트리로 풀었다.
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <limits.h>
using namespace std;
using int64 = long long;
int n, m;
vector<int> parent;
vector<int> height;
vector<pair<int64, int64>> v;
vector<pair<double, pair<int64, int64>>> dists;
double GetDist(pair<int64, int64>& loc1, pair<int64, int64>& loc2) {
return sqrt(pow(loc2.first - loc1.first, 2) + pow(loc2.second - loc1.second, 2));
}
int GetParent(int a) {
if (a == parent[a]) return a;
return parent[a] = GetParent(parent[a]);
}
void Merge(int u, int v) {
u = GetParent(u);
v = GetParent(v);
if (u == v) return;
if (height[u] > height[v])
::swap(u, v);
parent[u] = v;
if (height[u] == height[v])
height[v]++;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n >> m;
parent = vector<int>(n + 1);
height = vector<int>(n + 1, 1);
for (int i = 1; i <= n; i++) parent[i] = i;
v.push_back({ 0,0 });
for (int i = 1; i <= n; i++) {
int x, y;
cin >> x >> y;
v.push_back({ x,y });
}
double ans = 0;
for (int i = 0; i < m; i++) {
int x, y;
cin >> x >> y;
Merge(x, y);
}
for (int i = 1; i <= n; i++) {
for (int j = i + 1; j <= n; j++) {
dists.push_back({ GetDist(v[i],v[j]),{i,j} });
}
}
sort(dists.begin(), dists.end());
for (auto a : dists) {
int x = a.second.first;
int y = a.second.second;
if (GetParent(x) == GetParent(y)) continue;
Merge(x, y);
ans += a.first;
}
cout << fixed;
cout.precision(2);
cout << ans;
}
'알고리즘' 카테고리의 다른 글
백준 1485번 정사각형 C++ (0) | 2022.12.12 |
---|---|
백준 13904번 과제 C++ (0) | 2022.12.11 |
백준 1613번 역사 C++ (0) | 2022.12.09 |
백준 22352번 항체 인식 C++ (0) | 2022.12.08 |
백준 5212번 지구 온난화 C++ (0) | 2022.12.07 |