λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
Algorithm πŸ§‘πŸ»‍πŸ’»/λ°±μ€€(BOJ)

[λ°±μ€€,c++] 14950번 - μ •λ³΅μž

by dkswnkk 2021. 11. 14.

문제

 

14950번: μ •λ³΅μž

μ„œκ°• λ‚˜λΌλŠ” N개의 λ„μ‹œμ™€ M개의 λ„λ‘œλ‘œ μ΄λ£¨μ–΄μ‘Œλ‹€. λͺ¨λ“  λ„μ‹œμ˜ μŒμ—λŠ” κ·Έ λ„μ‹œλ₯Ό μ—°κ²°ν•˜λŠ” λ„λ‘œλ‘œ κ΅¬μ„±λœ κ²½λ‘œκ°€ μžˆλ‹€. 각 λ„λ‘œλŠ” μ–‘λ°©ν–₯ λ„λ‘œμ΄λ©°, 각 λ„λ‘œλŠ” μ‚¬μš©ν•˜λŠ”λ° ν•„μš”ν•œ λΉ„μš©μ΄ 쑴재

www.acmicpc.net

 

μ½”λ“œ

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int N, M, t; //N=λ„μ‹œμ˜ 개수(λ…Έλ“œ), M=λ„λ‘œμ˜ 개수(κ°„μ„ ), t=μ •λ³΅ν• λ•Œλ§ˆλ‹€ λ“œλŠ” λˆ„μ λΉ„μš©
vector<pair<int, pair<int, int>>>edges;
int parent[10001];
int ans = 0, cnt = 0;;

int findParent(int x) {
    if (x == parent[x]) return x;
    else return x = findParent(parent[x]);
}

void unionParent(int a, int b) {
    a = findParent(a);
    b = findParent(b);

    if (a < b) parent[b] = a;
    else parent[a] = b;
}
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);

    cin >> N >> M >> t;

    for (int i = 1; i <= N; i++) {    //λΆ€λͺ¨ ν…Œμ΄λΈ”μ—μ„œ, λΆ€λͺ¨μžμ‹ μ„ μžκΈ°μžμ‹ μœΌλ‘œ μ΄ˆκΈ°ν™”
        parent[i] = i;            
    }
    for (int i = 0; i < M; i++) {
        int a, b, c;
        cin >> a >> b >> c;
        edges.push_back({ c,{a,b} });    //λΉ„μš©μ„ κΈ°μ€€μœΌλ‘œ μ •λ ¬ν•˜κΈ° μœ„ν•΄ νŠœν”Œμ˜ 첫번째 μ›μ†Œμ— λΉ„μš© μ‚½μž…    
    }
    sort(edges.begin(), edges.end());

    for (int i = 0; i < edges.size(); i++) {
        int cost = edges[i].first;
        int a = edges[i].second.first;
        int b = edges[i].second.second;
        if (findParent(a) != findParent(b)) {
            unionParent(a, b);
            ans += cost+cnt*t;
            cnt++;
        }
    }
    cout << ans;
}

λŒ“κΈ€