백준 1967 nodejs

윤익·2022년 10월 31일
0

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

const fs = require('fs')
const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n')
const n = +input[0]
const tree = Array.from({length: n + 1}, _ => [])
for (let i = 1; i <= n - 1; i++) {
  const [p, c, l] = input[i].split(' ').map(Number)
  tree[p].push([c, l])
  tree[c].push([p, l])
}
function dfs(curr, l) {
  if (visited.has(curr)) return
  visited.add(curr)
  if (l > max) [node, max] = [curr, l]
  for ([next, nextL] of tree[curr]) dfs(next, l + nextL)
} 
// 한 정점에서 가장 먼 정점과 거리를 구함
let [node, max] = [0, 0]
const visited = new Set()
dfs(1, 0)
visited.clear()
dfs(node, 0)
// 2회 반복하면 트리의 지름을 구할 수 있음
console.log(max)
profile
https://nickyoon.tistory.com/ 기술 블로그 이전

0개의 댓글