๐ŸŽฒ๋ฐฑ์ค€ 11725๋ฒˆ ํŠธ๋ฆฌ์˜ ๋ถ€๋ชจ ์ฐพ๊ธฐ

Jeongeunยท2023๋…„ 6์›” 17์ผ
0

๋ฐฑ์ค€

๋ชฉ๋ก ๋ณด๊ธฐ
77/186

๋ฐฑ์ค€ 11725๋ฒˆ

๐Ÿ’Š ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋ฐœ์ƒํ–ˆ์—ˆ๋Š”๋ฐ ํƒ์ƒ‰ํ•œ ๋…ธ๋“œ๋ฅผ ์ฒดํฌํ•  ๋•Œ, checked ๋ฐฐ์—ด์—๋‹ค ๋…ธ๋“œ ๊ฐ’์„ pushํ•˜๊ณ  includes๋กœ ํ™•์ธํ–ˆ๋‹ค. ์ด ๋ถ€๋ถ„์„ ์•„๋ž˜ ์ฝ”๋“œ์™€ ๊ฐ™์ด ์ˆ˜์ •ํ•˜๋‹ˆ ๋งž์•˜๋‹ค.

์ฝ”๋“œ

const fs = require('fs'); 
const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
const N = +input.shift();

const tree = Array.from(new Array(N + 1), () => []);

for (let i = 0; i < N - 1; i++) {
  const [a, b] = input[i].split(" ").map(Number);
  tree[a].push(b);
  tree[b].push(a);
}

const parents = [];

let willCheck = [1];
let checked = new Array(N+1).fill(0);

while (willCheck.length) {
  const check = willCheck.pop();
  checked[check] = 1;
  for (let i = 0; i < tree[check].length; i++) {
    const child = tree[check][i];
    if (checked[child] === 0) {
      parents[child-2] = check;
      willCheck.push(child);
    }
  }
}


console.log(parents.join("\n"));

0๊ฐœ์˜ ๋Œ“๊ธ€