๋ณธ๋ฌธ์œผ๋กœ ๋ฐ”๋กœ๊ฐ€๊ธฐ
728x90
๐Ÿ”—๋ฌธ์ œ ๋ณด๋Ÿฌ๊ฐ€๊ธฐ
 

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

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

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
๋ฐ˜์‘ํ˜•