Algorithm/Baekjoon
[JavaScript/node.js] ๋ฐฑ์ค 3980๋ฒ - ์ ๋ฐ ๋ช ๋จ
๊ฐ๋ฐ๊ฐ๊ตด๐ธ
2022. 9. 3. 16:24
[๋ฌธ์ ]
https://www.acmicpc.net/problem/3980
[ํ์ด]
๋จ์ํ DFS๋ฅผ ํตํด ์ ์ ๋ฐฐ์น๊ฐ ๊ฐ๋ฅํ ๋ชจ๋ ์กฐํฉ์ ์์ ํ์ํ๋ ๋ฌธ์ ์์ต๋๋ค.
1. position ๋ฐฐ์ด์ ๊ฐ ์ ์๋ค์ ๊ฐ๋ฅํ ํฌ์ง์ ๊ณผ ๋ฅ๋ ฅ์ ์ ์ฅํฉ๋๋ค.
- position์ i๋ฒ์งธ ๋ฐฐ์ด์ [๊ฐ๋ฅํ ํฌ์ง์ , ๋ฅ๋ ฅ] ํํ๋ก pushํฉ๋๋ค.
๋ฐ๋ผ์ ์์ ์ position ์ ๋ณด๋ฅผ ๋ชจ๋ ์ ์ฅํ๋ฉด ๋ค์๊ณผ ๊ฐ์ต๋๋ค.
[
[ [ 0, 100 ] ],
[ [ 1, 80 ], [ 2, 70 ], [ 3, 70 ], [ 4, 60 ] ],
[ [ 1, 40 ], [ 2, 90 ], [ 3, 90 ], [ 4, 40 ] ],
[ [ 1, 40 ], [ 2, 85 ], [ 3, 85 ], [ 4, 33 ] ],
[ [ 1, 70 ], [ 2, 60 ], [ 3, 60 ], [ 4, 85 ] ],
[ [ 5, 95 ], [ 6, 70 ], [ 7, 60 ], [ 8, 60 ] ],
[ [ 1, 45 ], [ 5, 80 ], [ 6, 90 ], [ 7, 50 ], [ 8, 70 ] ],
[ [ 5, 40 ], [ 6, 90 ], [ 7, 90 ], [ 8, 40 ], [ 9, 70 ] ],
[ [ 6, 50 ], [ 7, 70 ], [ 8, 85 ], [ 9, 50 ] ],
[ [ 6, 66 ], [ 7, 60 ], [ 9, 80 ], [ 10, 80 ] ],
[ [ 6, 50 ], [ 7, 50 ], [ 9, 90 ], [ 10, 88 ] ]
]
2. DFS๋ฅผ ํตํด 11๋ช ์ ํฌ์ง์ ์ ์ ํํ๊ณ ๊ฐ ๋ฅ๋ ฅ์ ํฉ์ ๋ํด์ค๋๋ค.
- visit๋ฐฐ์ด์ ํตํด ์ด๋ฏธ ์ ํ๋ ํฌ์ง์ ๊ฐ์ ๊ด๋ฆฌํฉ๋๋ค.
- ๋ง์ฝ 11๋ฒ์งธ ์ ์๊น์ง ํฌ์ง์ ์ ๋ฑ๋กํ๋ฉด DFS์ returnํฉ๋๋ค. (0~10๋ฒ ์ ์๋ฅผ ๋ชจ๋ ๋ฑ๋กํ๊ณ idx 11์ผ ๋)
๋ฐ๋ผ์ ๋ฅ๋ ฅ์น ํฉ์ ์ต๋๋ฅผ ๊ตฌํ๋ฉด 970์ด ๋ฉ๋๋ค.
[์ฝ๋]
const fs = require('fs');
const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt';
const input = fs.readFileSync(filePath).toString().split('\n');
const [C] = input[0].split(" ").map(Number);
let max = 0;
const dfs = (position, idx, visit, total) => {
if(idx === 11) {
if(total > max) {
max = total;
}
return;
}
position[idx].forEach(element => {
const [i, score] = element;
if(!visit[i]) {
visit[i] = true;
dfs(position, idx + 1, visit, total + score);
visit[i] = false
}
});
}
const setPosition = (position) => {
const visit = Array.from({length: 11}, () => false);
dfs(position, 0, visit, 0);
}
for(let i=0;i<C;i++) {
const position = Array.from({length: 11}, () => []);
max = 0;
for(let j=0;j<11;j++) {
const temp = input[11*i+1 + j].split(" ").map(Number);
for(let k=0;k<11;k++) {
if(temp[k] > 0) {
position[j].push([k, temp[k]]);
}
}
}
setPosition(position);
console.log(max);
}