[Programmers] Lv3. ν•©μŠΉ νƒμ‹œ μš”κΈˆ | C++

2024. 1. 16. 16:58ㆍCoding Test/Programmers

πŸ”—λ¬Έμ œ λ³΄λŸ¬κ°€κΈ°
 

ν”„λ‘œκ·Έλž˜λ¨ΈμŠ€

μ½”λ“œ μ€‘μ‹¬μ˜ 개발자 μ±„μš©. μŠ€νƒ 기반의 ν¬μ§€μ…˜ 맀칭. ν”„λ‘œκ·Έλž˜λ¨ΈμŠ€μ˜ 개발자 λ§žμΆ€ν˜• ν”„λ‘œν•„μ„ λ“±λ‘ν•˜κ³ , λ‚˜μ™€ 기술 ꢁ합이 잘 λ§žλŠ” 기업듀을 맀칭 λ°›μœΌμ„Έμš”.

programmers.co.kr

 

πŸ§‘πŸ»‍πŸ’» 풀이 κ³Όμ •

 

[1μ°¨ μ‹œλ„] λ‹€μ΅μŠ€νŠΈλΌ μ•Œκ³ λ¦¬μ¦˜ (μ‹€νŒ¨)

 

μΆœλ°œμ§€(s)λ‘œλΆ€ν„° 각 λ…Έλ“œμ— λŒ€ν•œ μ΅œλ‹¨ 경둜 배열을 ꡬ해놓고, 각 λ…Έλ“œ(i)λ§ˆλ‹€ λ‹€μ΅μŠ€νŠΈλΌ μ•Œκ³ λ¦¬μ¦˜μ„ λŒλ €μ„œ sπŸ‘‰πŸ»i + iπŸ‘‰πŸ»a + iπŸ‘‰πŸ»b κ°’λ“€ 쀑 μ΅œμ†Ÿκ°’μ„ κ΅¬ν•˜λŠ” λ°©μ‹μœΌλ‘œ ν’€μ—ˆμŠ΅λ‹ˆλ‹€. λ…Έλ“œμ˜ 개수(N)κ°€ μ΅œλŒ€ 200개라 될 쀄 μ•Œμ•˜λŠ”λ° νš¨μœ¨μ„± ν…ŒμŠ€νŠΈμ—μ„œ μ‹œκ°„ μ΄ˆκ³Όκ°€ λ‚˜λ”κ΅°μš”.

 

[2μ°¨ μ‹œλ„] ν”Œλ‘œμ΄λ“œ μ›Œμ…œ μ•Œκ³ λ¦¬μ¦˜ (성곡)

 

맀 λ…Έλ“œλ§ˆλ‹€ λ‹€μ΅μŠ€νŠΈλΌ μ•Œκ³ λ¦¬μ¦˜μ„ 돌린 것이 원인이라 μƒκ°λ˜μ–΄, λͺ¨λ“  λ…Έλ“œ κ°„μ˜ μ΅œλ‹¨ 경둜λ₯Ό ꡬ할 수 μžˆλŠ” ν”Œλ‘œμ΄λ“œ μ›Œμ…œ μ•Œκ³ λ¦¬μ¦˜μ„ μ‚¬μš©ν–ˆμŠ΅λ‹ˆλ‹€. 사싀 μ˜›λ‚ μ— 써 보고 μ•ˆ μ¨μ„œ 기얡이 μ•ˆ λ‚¬λŠ”λ°, κ°„λ‹¨ν•œ μ•Œκ³ λ¦¬μ¦˜μ΄λΌ 빨리 κ³΅λΆ€ν•˜κ³  ν’€ 수 μžˆμ—ˆλ„€μš”.

 

 

βœοΈμ†ŒμŠ€ μ½”λ“œ 및 κ²°κ³Ό

#include <vector>
using namespace std;
using uint32 = unsigned int;
#define INF 3000000000

void FloydWarshall(vector<vector<uint32>>& graph, int n)
{
    for (int mid = 1; mid <= n; mid++)
        for (int from = 1; from <= n; from++)
            for (int to = 1; to <= n; to++)
                graph[from][to] = min(graph[from][to], graph[from][mid] + graph[mid][to]);
}

int solution(int n, int s, int a, int b, vector<vector<int>> fares) {

    // 1. Input Initialize
    vector<vector<uint32>> graph(n + 1, vector<uint32>(n + 1, INF));
    for (int i = 1; i <= n; i++)
        graph[i][i] = 0;
    
    for (const vector<int>& fare : fares)
    {
        uint32 from = fare[0], to = fare[1], cost = fare[2];
        graph[from][to] = graph[to][from] = cost;
    }

    // 2. Floyd-Warshall Algorithm
    FloydWarshall(graph, n);
    uint32 answer = INF;

    for (int i = 1; i <= n; i++)
        answer = min(answer, graph[s][i] + graph[i][a] + graph[i][b]);
    return answer;
}

 

 

728x90
λ°˜μ‘ν˜•