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

[๋ฐฑ์ค€,c++] 14621๋ฒˆ - ๋‚˜๋งŒ ์•ˆ๋˜๋Š” ์—ฐ์• 

by dkswnkk 2021. 11. 11.

๋ฌธ์ œ

 

14621๋ฒˆ: ๋‚˜๋งŒ ์•ˆ๋˜๋Š” ์—ฐ์• 

์ž…๋ ฅ์˜ ์ฒซ์งธ ์ค„์— ํ•™๊ต์˜ ์ˆ˜ N์™€ ํ•™๊ต๋ฅผ ์—ฐ๊ฒฐํ•˜๋Š” ๋„๋กœ์˜ ๊ฐœ์ˆ˜ M์ด ์ฃผ์–ด์ง„๋‹ค. (2 ≤ N ≤ 1,000) (1 ≤ M ≤ 10,000) ๋‘˜์งธ ์ค„์— ๊ฐ ํ•™๊ต๊ฐ€ ๋‚จ์ดˆ ๋Œ€ํ•™๊ต๋ผ๋ฉด M, ์—ฌ์ดˆ ๋Œ€ํ•™๊ต๋ผ๋ฉด W์ด ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ M๊ฐœ์˜

www.acmicpc.net

 

์ฝ”๋“œ

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

using namespace std;
int N, M;    //N=ํ•™๊ต์˜ ์ˆ˜(๋…ธ๋“œ) M=๋„๋กœ์˜ ์ˆ˜(๊ฐ„์„ )
int parent[1001];
char gender[1001];
int ans = 0;
bool flag[1001];
vector<pair<int, pair<int, int>>> edges;

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;
    for (int i = 1; i <= N; i++) {    //๋ถ€๋ชจํ…Œ์ด๋ธ” ์ƒ์—์„œ ๋ถ€๋ชจ๋ฅผ ์ž๊ธฐ์ž์‹ ์œผ๋กœ ์ดˆ๊ธฐํ™” ๋ฐ ์„ฑ๋ณ„์ •๋ณด ์ž…๋ ฅ
        char sex; cin >> sex;
        parent[i] = i;
        gender[i] = sex;
    }

    for (int i = 0; i < M; i++) {
        int u, v, d; cin >> u >> v >> d;
        edges.push_back({ d,{u,v} });    //๊ฑฐ๋ฆฌ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌํ•˜๊ธฐ ์œ„ํ•ด ๊ฑฐ๋ฆฌ๋ฅผ ํŠœํ”Œ์˜ ์ฒซ๋ฒˆ์งธ ์›์†Œ๋กœ ์ž…๋ ฅ
    }
    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 (gender[a] == gender[b]) continue;    //์„ฑ๋ณ„์ด ๊ฐ™์œผ๋ฉด ๋ฌด์‹œ
        if (findParent(a) != findParent(b)) {
            ans += cost;
            unionParent(a, b);
            flag[a] = flag[b] = true;    //ํ•ด๋‹น ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธํ–ˆ์œผ๋‹ˆ TRUE์ฒ˜๋ฆฌ
        }
    }
    for (int i = 1; i <= N; i++) {    //ํ•œ๋ฒˆ์ด๋ผ๋„ ๋ฐฉ๋ฌธ ํ•˜์ง€ ์•Š์€ ๋…ธ๋“œ๊ฐ€ ์žˆ๋‹ค๋ฉด ์—ฐ๊ฒฐx 
        if (!flag[i]) {
            cout << -1;
            return 0;
        }
    }
    cout << ans;
    return 0;
}

๋Œ“๊ธ€