๋ฌธ์
https://www.acmicpc.net/problem/1916
ํ์ด
์ฒ์์ dfs๋ก ์ ๊ทผํด์ ํ์๋๋ฐ ์๊ฐ์ด๊ณผ๋ก ํ๋ ค์ dp๋ฅผ ์ด์ฉํ๋ค.
์ผ๋จ map์ด๋ผ๋ 2์ฐจ์ ๋ฐฐ์ด์ ๊ตฌํํ๋ค. ์ด 2์ฐจ์ ๋ฐฐ์ด์ map[ i ][ j ] ๋ i๋์์์ j ๋์๋ก ๊ฐ ์ ๊ฐ์ฅ ๊ฐ๊ฒฉ์ด ์ผ ๋ฒ์ค ์๊ธ์ ๋ํ ๋ธ๋ค. ๋ง์ฝ map[ i ][ j ] = Infinity ์ด๋ฉด ํด๋น ๋ฃจํธ๋ ๋ฒ์ค๊ฐ ๋ค๋์ง ์๋๋ค๊ณ ์๊ฐํ๋ฉด ๋๋ค.
๊ทธ๋ฆฌ๊ณ dp๋ผ๋ 2์ฐจ์ ๋ฐฐ์ด์ ๊ตฌํํ๋ค.
dp[ i ][ j ] ๋ i ๋์์์ j ๋์๋ก ๊ฐ๋ ๋ฃจํธ๋ ๊ฐ์ฅ ๋ฒ์ค์๊ธ์ด ์ผ ๋ฃจํธ์ ์๊ธ์ ๋ํ๋ธ๋ค.
์ฐ๋ฆฌ๋ ๋ชจ๋ ๊ฒฝ๋ก๋ฅผ ํ์ํ๋ฉด์ 2์ฐจ์ ๋ฐฐ์ด dp๋ฅผ ์์ฑ์ํค๊ณ ์ต์ข ์ ์ผ๋ก dp[์ถ๋ฐ์ ][๋์ฐฉ์ ] => ์ต์๋น์ฉ ์ ๊ตฌํ๋ฉด ๋๋ค.
const fs = require("fs");
const input = fs.readFileSync("/dev/stdin").toString().trim().split("\n");
let [cityCnt, routeCnt, ...arr] = input;
cityCnt = Number(cityCnt);
routeCnt = Number(routeCnt);
let [start, end] = arr
.pop()
.split(" ")
.map((num) => Number(num));
// 2์ฐจ์ ๋ฐฐ์ด ์์ฑ ( ์๊ธ ํ์๋ฅผ ์ํด )
// map[i][j] => iํฌ์ธํธ์์ jํฌ์ธํธ๋ก ๊ฐ๋ ๋ฃจํธ์ ์๊ธ
let map = Array.from({ length: cityCnt + 1 }, () => {
return Array(cityCnt + 1).fill(Infinity);
});
for (let i = 0; i < arr.length; ++i) {
let [s, e, pay] = arr[i].split(" ").map((num) => Number(num));
if (map[s][e] !== Infinity) {
map[s][e] = Math.min(pay, map[s][e]);
} else {
map[s][e] = pay;
}
}
let dp = Array.from({ length: cityCnt + 1 }, () => {
return Array(cityCnt + 1).fill(Infinity);
});
let rest = [];
for (let i = 1; i < cityCnt + 1; ++i) {
if (map[start][i] !== Infinity) {
dp[start][i] = map[start][i];
rest.push(i);
}
}
while (rest.length) {
let middlePoint = rest.shift();
for (let i = 1; i < cityCnt + 1; ++i) {
if (map[middlePoint][i] !== Infinity && dp[start][middlePoint] !== Infinity) {
if (dp[start][i] > dp[start][middlePoint] + map[middlePoint][i]) {
dp[start][i] = dp[start][middlePoint] + map[middlePoint][i];
if (!rest.includes(i)) {
rest.push(i);
}
}
}
}
}
console.log(dp[start][end]);
'๐Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๋ฐฑ์ค[node.js] > 1966๋ฒ ์ ์ถ (0) | 2024.11.20 |
---|---|
๋ฐฑ์ค [nodejs] > 1629๋ฒ ๊ณฑ์ (0) | 2024.11.17 |
๋ฐฑ์ค[node.js] > 11660๋ฒ ๊ตฌ๊ฐ ํฉ ๊ตฌํ๊ธฐ5 (0) | 2024.11.14 |
๋ฐฑ์ค[nodejs] > 9465๋ฒ ์คํฐ์ปค (1) | 2024.11.13 |
๋ฐฑ์ค[node.js] > 1181๋ฒ ๋จ์ด ์ ๋ ฌ (0) | 2024.11.12 |