kokoball의 devlog
article thumbnail
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
profile

kokoball의 devlog

@kokoball-dev

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!