728x90
๐๋ฌธ์ ๋ณด๋ฌ๊ฐ๊ธฐ
๐ง๐ป๐ป ํ์ด ๊ณผ์
[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
๋ฐ์ํ
'๐คAlgorithm > Programmers' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Programmers] Lv3. ๋ถ๋๋ณต๊ท | C++ (0) | 2024.01.13 |
---|---|
[Programmers] Lv3. [1์ฐจ] ์ ํ๋ฒ์ค | C++ (0) | 2023.11.18 |
[Programmers] Lv3. ์ฌ ์ฐ๊ฒฐํ๊ธฐ | C++ (1) | 2023.10.22 |
[Programmers] Lv3. ๊ฐ์ฅ ๋จผ ๋ ธ๋ | C++ (0) | 2023.10.22 |
[Programmers] Lv3. [์นด์นด์ค ์ธํด] ๋ณด์ ์ผํ | C++ (0) | 2023.10.22 |