백준 1068 nodejs

윤익·2022년 10월 29일
0

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

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

function delLeaf(D) {
  if (!C[D].length) leaf--
  else C[D].forEach(i => delLeaf(i))
}

const N = +input[0]
const P = input[1].split(' ').map(Number)
const D = +input[2]

const C = Array.from({length: N}, _ => [])
P.forEach((p, c) => p != -1 && C[p].push(c))
// 각 노드의 자식 정보를 담은 배열 C 생성
let leaf = C.reduce((x, y) => (y.length ? x : ++x), 0) // 전체 leaf
if (P[D] != -1 && C[P[D]].length == 1) leaf++ 
// 삭제된 leaf의 부모가 leaf가 될 경우
delLeaf(D) // delete된 leaf 삭제
console.log(leaf)
profile
https://nickyoon.tistory.com/ 기술 블로그 이전

0개의 댓글