회원가입
로그인
Toggle navigation
문제
문제
전체 문제
문제 출처
단계별로 풀어보기
알고리즘 분류
추가된 문제
문제 순위
문제
푼 사람이 한 명인 문제
아무도 못 푼 문제
최근 제출된 문제
최근 풀린 문제
랜덤
출처
ICPC
Olympiad
한국정보올림피아드
한국정보올림피아드시․도지역본선
전국 대학생 프로그래밍 대회 동아리 연합
대학교 대회
카카오 코드 페스티벌
Coder's High
ICPC
Regionals
World Finals
Korea Regional
Africa and the Middle East Regionals
Europe Regionals
Latin America Regionals
North America Regionals
South Pacific Regionals
문제집
대회
채점 현황
게시판
그룹
더 보기
재채점 기록
블로그
도움말
전체
공지
자유
질문
오타/오역/요청
게시판 공지
홍보
업데이트
solved.ac
글쓰기
질문 도움말
자주묻는 질문
시간초과가 왜 나는지 모르겠습니다...
1753번 - 최단경로
jgw6372
2년 전
1
다익스트라 알고리즘으로 코드를 작성했습니다. 근데, 시간 초과가 어디서 나는지 잘 모르겠습니다.....
class Heap { constructor() { this.heap = [null]; } push(value) { this.heap.push(value); let currentIndex = this.heap.length - 1; let parentIndex = Math.floor(currentIndex / 2); while(parentIndex !== 0 && this.heap[parentIndex].cost > this.heap[currentIndex].cost) { this._swap(parentIndex, currentIndex); currentIndex = parentIndex; parentIndex = Math.floor(currentIndex / 2); } } pop() { if(this.isEmpty()) return; if(this.heap.length === 2) return this.heap.pop(); const returnValue = this.heap[1]; this.heap[1] = this.heap.pop(); let currentIndex = 1; let leftIndex = currentIndex * 2; let rightIndex = (currentIndex * 2) + 1; while( (this.heap[leftIndex] && this.heap[leftIndex].cost > this.heap[currentIndex].cost) || (this.heap[rightIndex] && this.heap[rightIndex].cost > this.heap[currentIndex].cost) ) { if(this.heap[leftIndex] === undefined) { this._swap(rightIndex, currentIndex); } else if(this.heap[rightIndex] === undefined) { this._swap(leftIndex, currentIndex); } else if(this.heap[leftIndex].cost > this.heap[rightIndex]) { this._swap(rightIndex, currentIndex); } else if(this.heap[leftIndex].cost < this.heap[rightIndex]) { this._swap(leftIndex, currentIndex); } } return returnValue; } isEmpty() { return this.heap.length === 1; } _swap(a, b) { [this.heap[a], this.heap[b]] = [this.heap[b], this.heap[a]]; } } const fs = require('fs'); const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n'); const [V, M] = input.shift().split(' ').map(Number); const startNode = Number(input.shift()); const costs = []; for(const cost of input) { costs.push(cost.split(' ').map(Number)); } const heap = new Heap(); const dist = new Array(V + 1).fill(Infinity); heap.push({node: startNode, cost: 0}); dist[startNode] = 0; while(!heap.isEmpty()) { const { node: currentNode, cost: currentCost } = heap.pop(); for(const [src, dest, cost] of costs) { const nextCost = cost + currentCost; if(src === currentNode && nextCost < dist[dest]) { heap.push({node: dest, cost: nextCost}); dist[dest] = nextCost; } } } console.log( dist .map((element) => Number.isFinite(element) ? element : 'INF') .slice(1) .join('\n') );
댓글을 작성하려면
로그인
해야 합니다.
jgw6372 2년 전 1
다익스트라 알고리즘으로 코드를 작성했습니다. 근데, 시간 초과가 어디서 나는지 잘 모르겠습니다.....