1일1알

백준 1922번 네트워크 연결 C++ 본문

알고리즘

백준 1922번 네트워크 연결 C++

영춘권의달인 2022. 8. 9. 09:49

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

 

기본적인 최소 스패닝 트리 문제인 것 같다. 유니온 파인드를 이용해서 풀었다.

 

#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 Computer {
    int a;
    int b;
    int cost;
    bool operator<(const Computer& other)const {
        return cost < other.cost;
    }
};

vector<int> parent;
vector<int> height;

int GetParnet(int n) {
    if (n == parent[n])
        return n;
    return parent[n] = GetParnet(parent[n]);
}

void Merge(int u, int v) {
    u = GetParnet(u);
    v = GetParnet(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);

    cin >> n >> m;

    parent = vector<int>(n + 1);
    height = vector<int>(n + 1, 1);

    for (int i = 1; i <= n; i++) {
        parent[i] = i;
    }

    int ans = 0;
    vector<Computer> computers;
    for (int i = 0; i < m; i++) {
        int a, b, cost;
        cin >> a >> b >> cost;
        computers.push_back({ a,b,cost });
    }

    sort(computers.begin(), computers.end());

    for (auto a : computers) {
        if (GetParnet(a.a) == GetParnet(a.b)) continue;
        Merge(a.a, a.b);
        ans += a.cost;
    }

    cout << ans;
}

'알고리즘' 카테고리의 다른 글

백준 1261번 알고스팟 C++  (0) 2022.08.11
백준 3055번 탈출 C++  (0) 2022.08.10
백준 1707번 이분 그래프 C++  (0) 2022.08.08
백준 1976번 여행 가자 C++  (0) 2022.08.07
백준 1039번 교환 C++  (0) 2022.08.06