알고리즘
백준 6497번 전력난 C++
영춘권의달인
2022. 8. 30. 10:11
유니온 파인드 자료구조를 이용해서 최소 스패닝 트리를 구하여 절약할 수 있는 최대 비용을 구했다.
#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";
}
}