๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/๋ฐฑ์ค€(BOJ)

[๋ฐฑ์ค€,c++] 1197๋ฒˆ - ์ตœ์†Œ ์ŠคํŒจ๋‹ ํŠธ๋ฆฌ

by dkswnkk 2021. 11. 2.
 

1197๋ฒˆ: ์ตœ์†Œ ์ŠคํŒจ๋‹ ํŠธ๋ฆฌ

์ฒซ์งธ ์ค„์— ์ •์ ์˜ ๊ฐœ์ˆ˜ V(1 ≤ V ≤ 10,000)์™€ ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜ E(1 ≤ E ≤ 100,000)๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ E๊ฐœ์˜ ์ค„์—๋Š” ๊ฐ ๊ฐ„์„ ์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ์„ธ ์ •์ˆ˜ A, B, C๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์ด๋Š” A๋ฒˆ ์ •์ ๊ณผ B๋ฒˆ ์ •์ ์ด

www.acmicpc.net

//  Copyright © 2021 ์•ˆ์ฃผํ˜•. All rights reserved.
//  ํฌ๋ฃจ์Šค์นผ ์•Œ๊ณ ๋ฆฌ์ฆ˜(์ตœ์†Œ์ŠคํŒจ๋‹ ํŠธ๋ฆฌ)
//  https://www.acmicpc.net/problem/1197
//  BOJ1197 ์ตœ์†Œ ์ŠคํŒจ๋‹ ํŠธ๋ฆฌ

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


using namespace std;
int V, E;    // V=์ •์ ์˜ ๊ฐœ์ˆ˜, E=๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜
int parent[10001];    //๋ถ€๋ชจ ํ…Œ์ด๋ธ” ์ดˆ๊ธฐํ™”
vector<pair<int, pair<int, int>>>edges;    //๋ชจ๋“  ๊ฐ„์„ ์„ ๋‹ด์„ ๋ฆฌ์ŠคํŠธ์™€, ์ตœ์ข… ๋น„์šฉ์„ ๋‹ด์„ ๋ณ€์ˆ˜
int ans = 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 >> V >> E;

    for (int i = 1; i <= V; i++) {    //๋ถ€๋ชจ ํ…Œ์ด๋ธ”์ƒ์—์„œ, ๋ถ€๋ชจ๋ฅผ ์ž๊ธฐ ์ž์‹ ์œผ๋กœ ์ดˆ๊ธฐํ™”
        parent[i] = i;
    }

    for (int i = 0; i < E; i++) {    //๋ชจ๋“  ๊ฐ„์„ ์— ๋Œ€ํ•œ ์ •๋ณด ์ž…๋ ฅ
        int a, b, cost;
        cin >> a >> b >> cost;
        edges.push_back({ cost, { 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;
        }
    }
    cout << ans;
}

๋Œ“๊ธ€