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
- XR Interaction Toolkit
- 우선순위 큐
- 자료구조
- 백트래킹
- c++
- DFS
- 시뮬레이션
- 수학
- Team Fortress 2
- Unreal Engine 5
- ue5
- BFS
- 그래프
- 재귀
- 백준
- 브루트포스
- 구현
- 누적 합
- 문자열
- 그리디 알고리즘
- 트리
- 다익스트라
- 정렬
- 투 포인터
- 유니티
- 스택
- VR
- 유니온 파인드
- 알고리즘
- 다이나믹 프로그래밍
Archives
- Today
- Total
1일1알
백준 6497번 전력난 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>
#include <bitset>
using namespace std;
using int64 = long long;
struct Info {
int house1;
int house2;
int dist;
bool operator<(const Info& other) const {
return dist < other.dist;
}
bool operator>(const Info& other) const {
return dist > other.dist;
}
};
vector<int> parent;
vector<int> height;
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] = v;
if (height[u] == height[v])
height[v]++;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
while (true) {
int m, n;
cin >> m >> n;
if (m == 0 && n == 0) break;
parent = vector<int>(m);
for (int i = 0; i < m; i++)
parent[i] = i;
height = vector<int>(m, 1);
int sum = 0;
vector<Info> infos;
for (int i = 0; i < n; i++) {
int house1, house2, dist;
cin >> house1 >> house2 >> dist;
sum += dist;
infos.push_back({ house1,house2,dist });
}
sort(infos.begin(), infos.end());
int minSum = 0;
for (auto a : infos) {
if (GetParent(a.house1) == GetParent(a.house2)) continue;
Merge(a.house1, a.house2);
minSum += a.dist;
}
cout << sum - minSum << "\n";
}
}
'알고리즘' 카테고리의 다른 글
백준 16197번 두 동전 C++ (0) | 2022.09.01 |
---|---|
백준 16562번 친구비 C++ (0) | 2022.08.31 |
백준 10282번 해킹 C++ (0) | 2022.08.29 |
백준 17836번 공주님을 구해라! C++ (0) | 2022.08.28 |
백준 2665번 미로만들기 C++ (0) | 2022.08.26 |