개발자 톡

연습문제 톡 [21년 재직자 대회 본선] 거리 합 구하기

[2021 재직자 대회 본선] 거리 합 구하기 런타임 에러 질문 (nodejs)

등록일
2023-02-16 00:17:42
조회수
480
작성자
ney9083

const filePath = process.platform === "linux" ? "/dev/stdin" : "input.txt";
const input = require("fs")
  .readFileSync(filePath)
  .toString()
  .trim()
  .split("\n");

function solution(n, arr) {
  const graph = Array.from({ length: n + 1 }, () => new Array());
  const subTreeSizeList = Array.from({ length: n + 1 }, () => 0);
  const distanceSumList = Array.from({ length: n + 1 }, () => 0);
  for (let i = 0; i < arr.length; i++) {
    const [a, b, c] = arr[i];
    graph[a].push([b, c]);
    graph[b].push([a, c]);
  }
  const dfs1 = (current, parent) => {
    subTreeSizeList[current] = 1;
    for (let i = 0; i < graph[current].length; i++) {
      const child = graph[current][i][0];
      const weight = graph[current][i][1];
      if (child !== parent) {
        dfs1(child, current);
        distanceSumList[current] +=
          distanceSumList[child] + subTreeSizeList[child] * weight;
        subTreeSizeList[current] += subTreeSizeList[child];
      }
    }
  };

  const dfs2 = (current, parent) => {
    for (let i = 0; i < graph[current].length; i++) {
      const child = graph[current][i][0];
      const weight = graph[current][i][1];
      if (child !== parent) {
        distanceSumList[child] =
          distanceSumList[current] + weight * (n - 2 * subTreeSizeList[child]);
        dfs2(child, current);
      }
    }
  };
  dfs1(1, 1);
  dfs2(1, 1);

  for (let i = 1; i <= n; i++) {
    console.log(distanceSumList[i]);
  }
}

const N = +input[0];
const arr = input.slice(1).map((i) => i.split(" ").map(Number));
solution(N, arr);


다익스트라, 플로이드워셜이 터져서 유튜브에 해설 강의를 보면서 JS로 옮긴 알고리즘입니다.

하지만  32-234-2, 54-2,  50-2, 52-2 에서 계속 런타임 에러가 발생하는데 

그 이유를 모르겠습니다.

런타임 에러가 발생하는 이유가 있을까요?




#[21년_재직자_대회_본선]_거리_합_구하기
#nodejs

이 카테고리의 톡 더보기