[Programmers] Lv3. ์„ฌ ์—ฐ๊ฒฐํ•˜๊ธฐ | C++

2023. 10. 22. 16:40ใ†Coding Test/Programmers

๐Ÿ”—๋ฌธ์ œ ๋ณด๋Ÿฌ๊ฐ€๊ธฐ
 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

๐Ÿง‘‍๐Ÿ’ปํ’€์ด ๊ณผ์ •

 

๐Ÿ”—์ตœ์†Œ ์‹ ์žฅ ํŠธ๋ฆฌ(MST, Minimum Spanning Tree)๋ฅผ ํ™œ์šฉํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค. ์ตœ์†Œ ์‹ ์žฅ ํŠธ๋ฆฌ๋ฅผ ๊ตฌ์ถ•ํ•˜๋Š” ๊ณผ์ •์—์„œ ํฌ๋ฃจ์Šค์นผ(Kruskal) ๋˜๋Š” ํ”„๋ฆผ(Prim)์˜ ์•Œ๊ณ ๋ฆฌ์ฆ˜์ด ์‚ฌ์šฉ๋˜๋ฉฐ, ์ €๋Š” ํฌ๋ฃจ์Šค์นผ(Kruskal)์˜ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์‚ฌ์šฉํ•˜์—ฌ ํ’€์—ˆ์Šต๋‹ˆ๋‹ค.

 

์‹ ์žฅ ํŠธ๋ฆฌ์˜ ์กฐ๊ฑด ์ค‘ ํ•˜๋‚˜๋กœ ์‚ฌ์ดํด์ด ์žˆ์œผ๋ฉด ์•ˆ๋œ๋‹ค๊ฐ€ ์žˆ๋Š”๋ฐ, ๋ถ„๋ฆฌ ์ง‘ํ•ฉ(Disjoint set)์˜ ๊ฐœ๋…์ธ ๐Ÿ”—์œ ๋‹ˆ์˜จ ํŒŒ์ธ๋“œ(Union Find)๋ผ ๋ถˆ๋ฆฌ๋Š” ์ž๋ฃŒ๊ตฌ์กฐ๋กœ ์‰ฝ๊ฒŒ ์ ๊ฒ€ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

์ด๋ฒˆ ๊ธฐํšŒ์— ๊ณต๋ถ€ํ•˜์—ฌ ๊ฐœ๋…์„ ํ•™์Šต ํ›„, ์ด๋ฅผ ํ™œ์šฉํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ’€์–ด๋ณด์•˜์Šต๋‹ˆ๋‹ค. ์ œ๊ฐ€ ์ด๊ฑธ ์•Œ์•˜๋”๋ผ๋ฉด, NC Soft ์ฝ”๋”ฉ ํ…Œ์ŠคํŠธ์—์„œ ํ•œ ๋ฌธ์ œ๋Š” ๊ทธ๋ƒฅ ํ’€๊ณ  ๋„˜์–ด๊ฐ”์„ํ…๋ฐ ๋ง์ด์ฃ ... ์•„์‰ฝ๋„ค์š”.

 

โœ๏ธ์†Œ์Šค ์ฝ”๋“œ ๋ฐ ๊ฒฐ๊ณผ

#include <vector>
#include <algorithm>
using namespace std;

class DisjointSet
{
public:
    DisjointSet(int n) : parent(n), rank(n, 1)
    {
        for (int i = 0; i < n; i++)
            parent[i] = i;
    }

    int Find(int node)
    {
        if (parent[node] == node)
            return node;
        return parent[node] = Find(parent[node]);
    }

    void Merge(int node1, int node2)
    {
        node1 = Find(node1), node2 = Find(node2);
        if (node1 == node2)
            return;

        if (rank[node1] > rank[node2])
            swap(node1, node2);

        parent[node1] = node2;

        if (rank[node1] == rank[node2])
            rank[node2]++;
    }

    bool IsInSameSet(int node1, int node2)
    {
        node1 = Find(node1), node2 = Find(node2);
        return node1 == node2;
    }
private:
    vector<int> parent;
    vector<int> rank;
};

int solution(int n, vector<vector<int>> costs) {
    int answer = 0;
    DisjointSet ds(n);
    
    sort(costs.begin(), costs.end(), [](const vector<int>& c1, const vector<int>& c2) { return c1[2] < c2[2]; });
    for (const auto& cost : costs)
    {
        int node1 = cost[0], node2 = cost[1];
        if (ds.IsInSameSet(node1, node2))
            continue;

        ds.Merge(node1, node2);
        answer += cost[2];
    }

    return answer;
}

 

728x90
๋ฐ˜์‘ํ˜•