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 |
Tags
- 투 포인터
- 누적 합
- 백트래킹
- 다익스트라
- 유니온 파인드
- DFS
- BFS
- 문자열
- 구현
- 다이나믹 프로그래밍
- Unreal Engine 5
- 자료구조
- XR Interaction Toolkit
- Team Fortress 2
- 스택
- 백준
- ue5
- 시뮬레이션
- 유니티
- 재귀
- 그래프
- 정렬
- 그리디 알고리즘
- VR
- 알고리즘
- 브루트포스
- 트리
- c++
- 수학
- 우선순위 큐
Archives
- Today
- Total
1일1알
백준 1197번 최소 스패닝 트리 C++ 본문
유니온 파인드와 크루스칼 알고리즘을 이용해서 풀었다.
#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;
struct RouteCost {
int start;
int end;
int cost;
bool operator<(RouteCost& other) {
return cost < other.cost;
}
};
vector<int> parent;
vector<int> height;
vector<RouteCost> routes;
int GetParent(int n) {
if (n == parent[n])
return n;
parent[n] = GetParent(parent[n]);
return parent[n];
}
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);
int v, e;
cin >> v >> e;
parent = vector<int>(v + 1);
height = vector<int>(v + 1, 1);
for (int i = 1; i <= v; i++) {
parent[i] = i;
}
for (int i = 0; i < e; i++) {
int start, end, cost;
cin >> start >> end >> cost;
routes.push_back({ start,end,cost });
}
sort(routes.begin(), routes.end());
int64 sum = 0;
for (int i = 0; i < e; i++) {
int start = routes[i].start;
int end = routes[i].end;
int64 cost = routes[i].cost;
if (GetParent(start) == GetParent(end))
continue;
sum += cost;
Merge(start, end);
}
cout << sum;
}
'알고리즘' 카테고리의 다른 글
백준 10942번 팰린드롬? C++ (0) | 2022.07.07 |
---|---|
백준 1806번 부분합 C++ (0) | 2022.07.03 |
백준 2467번 용액 C++ (0) | 2022.07.01 |
백준 2166번 다각형의 면적 C++ (0) | 2022.06.30 |
백준 10830번 행렬 제곱 C++ (0) | 2022.06.29 |