728x90
문제
https://www.acmicpc.net/problem/1043
문제 해석
이 문제는 일반적인 그래프 연결 문제로 어렵지 않게 풀 수 있는 문제이다.
다만 풀이 과정에서 js 메서드를 잘 활용하면 훨씬 적은 양의 코드로 풀 수 있기에 기록해 둔다.
각 라인을 반복할 때 요소 중 하나라도 조건에 맞으면 true를 반환하는 some을 사용하면 더 효율적으로 풀 수 있다.
some() - true값 찾기
- 리턴값이 하나라도 true 라면 true값 반환
- 빈 배열에서 호출하면 false값 반환
const array = [1, 2, 3, 4, 5];
// checks whether an element is even
const even = (element) => element % 2 === 0;
console.log(array.some(even));
// expected output: true
every() - false값 찾기
- 리턴값이 모두 true라면 true값 반환 = 하나라도 false라면 false 반환
- 빈 배열에서 호출하면 true값 반환
const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));
// expected output: true
풀이
const filePath = process.platform === "linux" ? "dev/stdin" : "../test.txt";
const input = require("fs").readFileSync(filePath).toString().trim().split("\n");
function solution(input) {
const [n, m] = input[0].split(" ").map(Number);
const [trueMemberLength, ...members] = input[1].split(" ").map(Number);
const party = input.slice(2).map((l) => l.split(" ").slice(1).map(Number));
const truthSet = new Set(members);
for (let i = 0; i < n; i++) {
party.forEach((p) => {
const truthInParty = p.some((h) => truthSet.has(h));
if (truthInParty) {
p.forEach((h) => truthSet.add(h));
}
});
}
let count = 0;
party.forEach((p) => {
const truthInParty = p.some((h) => truthSet.has(h));
if (!truthInParty) {
count++;
}
});
return count;
}
console.log(solution(input));
끝
728x90
'WEB > 백준 문제 풀이' 카테고리의 다른 글
백준 15686 치킨 배달 (node.js) (0) | 2024.06.20 |
---|---|
백준 9663 N-Queen (node.js) (0) | 2024.06.19 |
백준 1922 네트워크 연결 (node.js) (0) | 2024.06.17 |
백준 11724 연결 요소의 개수 (node.js) (0) | 2024.06.13 |
백준 2606 바이러스 (node.js) (0) | 2024.06.12 |