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
- 다이나믹 프로그래밍
- ue5
- 다익스트라
- 유니티
- 백트래킹
- 시뮬레이션
- 수학
- c++
- 유니온 파인드
- 자료구조
- Unreal Engine 5
- 누적 합
- BFS
- 우선순위 큐
- 구현
- XR Interaction Toolkit
- 백준
- 투 포인터
- 재귀
- 스택
- 그리디 알고리즘
- 그래프
- 정렬
- Team Fortress 2
- 트리
- DFS
- VR
- 알고리즘
- 브루트포스
- 문자열
Archives
- Today
- Total
1일1알
백준 21924번 도시 건설 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;
int n, m;
struct Info {
int a;
int b;
int cost;
bool operator<(const Info& other) {
return cost < other.cost;
}
};
vector<int> parent;
vector<int> height;
vector<Info> Infos;
int GetParent(int n) {
if (n == parent[n])
return n;
return parent[n] = GetParent(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] = parent[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;
int64 totalSum = 0;
for (int i = 0; i < m; i++) {
int a, b, cost;
cin >> a >> b >> cost;
Infos.push_back({ a,b,cost });
totalSum += cost;
}
sort(Infos.begin(), Infos.end());
int64 sum = 0;
int cnt = 0;
for (int i = 0; i < Infos.size(); i++) {
if (GetParent(Infos[i].a) == GetParent(Infos[i].b))
continue;
Merge(Infos[i].a, Infos[i].b);
sum += Infos[i].cost;
cnt++;
}
int64 ans = totalSum - sum;
if (cnt < n - 1) ans = -1;
cout << ans;
}
'알고리즘' 카테고리의 다른 글
백준 1976번 여행 가자 C++ (0) | 2022.08.07 |
---|---|
백준 1039번 교환 C++ (0) | 2022.08.06 |
백준 10710번 실크로드 C++ (0) | 2022.08.03 |
백준 17142번 연구소 3 C++ (0) | 2022.08.02 |
백준 13460번 구슬 탈출 2 C++ (0) | 2022.08.01 |