반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 문자열
- 알고리즘
- 가천대
- 레벨 1
- TCP
- 수학
- 소켓
- 그래프
- BFS
- Crawling
- HTTP
- 크롤링
- Node.js
- 쉬운 문제
- typescript
- 자바스크립트
- ip
- socket
- HTTP 완벽 가이드
- javascript
- 타입 챌린지
- dfs
- dp
- 프로그래머스 레벨 2
- type challenge
- 타입스크립트
- 프로그래머스
- 백준
- Nestjs
- Algorithm
Archives
- Today
- Total
kakasoo
[node.js] 스타트와 링크 ( 백준 14889번 ) 본문
반응형
// 백준 14889번 스타트와 링크를 풀었습니다.
// 조합을 사용하여 풀었습니다.
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const combinations = function* (elements, selectNumber) {
for (let i = 0; i < elements.length; i++) {
if (selectNumber === 1) {
yield [elements[i]];
} else {
const fixed = elements[i];
const rest = elements.slice(i + 1);
for (const a of combinations(rest, selectNumber - 1)) {
yield [fixed, ...a];
}
}
}
};
const getAblilty = (team, map) => {
let sum = 0;
for (let i = 0; i < team.length; i++) {
const from = team[i];
for (let j = 0; j < team.length; j++) {
const to = team[j];
sum += map[from][to];
}
}
return sum;
};
const input = [];
rl.on("line", (line) => {
input.push(line);
}).on("close", () => {
const num = Number(input.splice(0, 1));
const map = [...input].map((el) => el.split(" ").map(Number));
const people = new Array(num).fill(0).map((el, i) => i);
let minValue = 987654321;
for (const a of combinations(people, num / 2)) {
const start = a;
const link = [...people].filter((el) => !start.includes(el));
const startAbility = getAblilty(start, map);
const linkAbility = getAblilty(link, map);
const difference = Math.abs(startAbility - linkAbility);
minValue = Math.min(minValue, difference);
}
console.log(minValue);
});
조합을 사용하여 한 쪽 집단을 구하고, 나머지 한 쪽 집단을 구한 후, 각각 점수를 구해서 차이를 비교해주면 된다.
answer 라는 배열을 만들어 최솟값들을 저장한 다음, Math.min(...answer) 형태로 구하고자 했는데
콜 스택 초과가 떴다.
경우의 수가 배열의 크기보다 크기 때문에 발생한 일이다.
콜 스택이라고 하면 함수의 재귀가 터진 것처럼 보이는데, 실제로는 배열이라서 볼 때마다 헷갈리곤 한다.
앞으로는 그 때 그 때 최솟값을 구해서 저장해둬야 겠다.
반응형
'프로그래밍 > 알고리즘 풀이' 카테고리의 다른 글
[node.js] 부등호 ( 백준 2529번 ) (0) | 2021.08.03 |
---|---|
[node.js] 부분 수열의 합( 백준 1182번 ) (0) | 2021.08.01 |
[node.js] 연산자 끼워넣기 ( 백준 14888번 ) (0) | 2021.07.31 |
[node.js] 로또 ( 백준 6603번 ) (0) | 2021.07.31 |
[node.js] 외판원 순회2 ( 백준 10971번 ) (0) | 2021.07.31 |