본문으로 건너뛰기
poylog

개발·AI

26069 붙임성 좋은 총총이

1분

https://www.acmicpc.net/problem/26069

백준 26069번 무지개 댄스 문제 설명과 토끼 일러스트
javascript
// test.txt
12
bnb2011 chansol
chansol chogahui05
chogahui05 jthis
jthis ChongChong
jthis jyheo98
jyheo98 lms0806
lms0806 pichulia
pichulia pjshwa
pjshwa r4pidstart
r4pidstart swoon
swoon tony9402
tony9402 bnb2011

Sol 1

javascript
const [N, ...input] = require("fs")
  .readFileSync("test.txt")
  .toString()
  .trim()
  .split("\n");

let arr = input.map((v) => v.split(" "));
let dance = ["ChongChong"];
for (let i = 0; i < N; i++) {
  for (let j = 0; j < dance.length; j++) {
    if (arr[i].includes(dance[j])) {
      arr[i].forEach((el) => dance.push(el));
      break;
    }
  }
}
let answer = dance.filter((el, i) => dance.indexOf(el) === i).length;
console.log(answer);

이중 for문을 통해 dance배열과 기록 하나를 비교한다. 기록에 dance 배열에 속한 사람이 있다면 일단 둘 다 dance 배열에 넣어둔 다음 마지막에 filter를 통해 중복을 제거해준다.

sol 2

javascript
const [_, ...input] = require("fs")
  .readFileSync("test.txt")
  .toString()
  .trim()
  .split("\n");
let arr = input.map((v) => v.split(" "));
let dance = new Set();
dance.add("ChongChong");
arr.forEach((v) => {
  if (dance.has(v[0]) || dance.has(v[1])) {
    dance.add(v[0]);
    dance.add(v[1]);
  }
});
console.log(dance.size);

첫 번째 방법은 일단 춤을 춘 사람이면 모두 dance 배열에 넣고 중복을 제거하는 작업을 한 번 더 해야 했다. 처음부터 중복해서 dance에 들어가지 않도록 Set을 사용해 size로 길이만 출력해주었다.

결과적으로 Set을 이용한 방법이 동일한 메모리를 사용하지만 더 빠르게 해결된다. 

백준 26069번 Node.js 제출 두 건 맞았습니다!! 결과