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 |
Tags
- Team Fortress 2
- 누적 합
- 유니티
- 트리
- 브루트포스
- c++
- 재귀
- 그리디 알고리즘
- 구현
- 스택
- 알고리즘
- 다익스트라
- 유니온 파인드
- XR Interaction Toolkit
- 투 포인터
- 문자열
- 자료구조
- 그래프
- VR
- DFS
- Unreal Engine 5
- 시뮬레이션
- 수학
- 백준
- ue5
- 정렬
- 우선순위 큐
- 다이나믹 프로그래밍
- BFS
- 백트래킹
Archives
- Today
- Total
1일1알
백준 1774번 우주신과의 교감 C++ 본문
https://www.acmicpc.net/problem/1774
유니온 파인드 자료구조를 이용해서 최소 스패닝 트리로 풀었다.
#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 |