๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐Ÿ“ ์•Œ๊ณ ๋ฆฌ์ฆ˜/Programmers

[C++/PGS] Lv.3 : ์„ฌ ์—ฐ๊ฒฐํ•˜๊ธฐ (๊ทธ๋ฆฌ๋”” Greedy)

728x90

 

https://school.programmers.co.kr/learn/courses/30/lessons/42861

 

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

SW๊ฐœ๋ฐœ์ž๋ฅผ ์œ„ํ•œ ํ‰๊ฐ€, ๊ต์œก, ์ฑ„์šฉ๊นŒ์ง€ Total Solution์„ ์ œ๊ณตํ•˜๋Š” ๊ฐœ๋ฐœ์ž ์„ฑ์žฅ์„ ์œ„ํ•œ ๋ฒ ์ด์Šค์บ ํ”„

programmers.co.kr

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ๊ทธ๋ฆฌ๋”” - ์„ฌ ์—ฐ๊ฒฐํ•˜๊ธฐ ๋ฌธ์ œ

 

์›๋ž˜๋Š” ๊ฐ ํŠธ๋ฆฌ์˜ ์ตœ์ƒ๋‹จ ๋ถ€๋ชจ๊ฐ’์„ ์žฌ๊ท€์ ์œผ๋กœ ์ฐพ๋Š” ๊ฒŒ ์ •์„ ํ’€์ด์ธ๋ฐ,

๋‚˜๋Š” ๋ณต์žกํ•ด์„œ ๊ทธ๋ƒฅ ์ธ๋ฑ์Šค ๋ฐฐ์—ด์— ์ตœ์†Œ ๋ถ€๋ชจ๊ฐ’๋งŒ ์ €์žฅํ•ด๋†“๊ณ  ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ๊ฐฑ์‹ ํ–ˆ๋‹ค.

 

1. ์ตœ์†Œ ์‹ ์žฅ ํŠธ๋ฆฌ๋ฅผ ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด, Greedy๋กœ ์ตœ์†Ÿ๊ฐ’ ๊ฐ„์„ ๋ถ€ํ„ฐ ์ฐพ๋Š” ๊ฒŒ ํฌ์ธํŠธ!

2. ๊ฐ ํŠธ๋ฆฌ์˜ ์ตœ์†Œ ๋ถ€๋ชจ๊ฐ’์„ ๋น„๊ตํ•ด์„œ, ๊ฐ™์œผ๋ฉด ํ•œ ํŠธ๋ฆฌ ๋‚ด๋ถ€์— ์žˆ๋Š” ๊ฒƒ์œผ๋กœ ๋ณด๊ณ , ๋‹ค๋ฅด๋‹ค๋ฉด ๋‘ ํŠธ๋ฆฌ๋ฅผ ์ด์–ด์คŒ.

 

 

๋‚˜์˜ ํ’€์ด

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

int indexParent[101] = {0,};
int n;

bool cmp(vector<int> a, vector<int> b){
    return a[2] < b[2];
}

void unionNodes(int start, int end){
    int big; int small;
    if(indexParent[start] < indexParent[end]){
        big = indexParent[end];
        small = indexParent[start];
    }
    else{
        small = indexParent[end];
        big = indexParent[start];
    }
    for(int i=0; i<n; ++i){
        if(indexParent[i]==big) indexParent[i] = small;
    }
    return;
}

int solution(int N, vector<vector<int>> costs) {
    n = N;
    int answer = 0;
    int size = costs.size();
    sort(costs.begin(), costs.end(), cmp);
    for(int i=0; i<n; ++i) indexParent[i] = i;
    
    for(auto cost: costs){
        int startNode = cost[0];
        int endNode = cost[1];
        int bridge = cost[2];
        if(indexParent[startNode] != indexParent[endNode]){ // ์ตœ์†Œ ๋ถ€๋ชจ๊ฐ’์ด ๋‹ค๋ฅด๋ฉด
            unionNodes(startNode, endNode); // ํŠธ๋ฆฌ ํ•ฉ์น˜๊ธฐ, ๋ถ€๋ชจ๊ฐ’ ๊ฐฑ์‹ 
            answer += bridge;
        }
        
        bool isEnd = true;
        for(int i=0; i<n-1; ++i){
            if(indexParent[i] != indexParent[i+1]) {
                isEnd = false;
                break;
            }
        }
        if(isEnd) break;
    }
    
    return answer;
}
728x90