1일1알

백준 6497번 전력난 C++ 본문

알고리즘

백준 6497번 전력난 C++

영춘권의달인 2022. 8. 30. 10:11

출처 : https://www.acmicpc.net/problem/6497

 

유니온 파인드 자료구조를 이용해서 최소 스패닝 트리를 구하여 절약할 수 있는 최대 비용을 구했다.

 

#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