새소식

코테 준비/Java

[백준] #1446. 지름길 (실버 1)

  • -

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

import java.io.*;
import java.util.*;

class Node implements Comparable<Node> {
	int idx;
	int cost;

	// 생성자
	Node(int idx, int cost) {
		this.idx = idx;
		this.cost = cost;
	}

	@Override
	public int compareTo(Node other) {
		return Integer.compare(this.cost, other.cost);
	}
}

public class Main {
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());

		int N = Integer.parseInt(st.nextToken());  //지름길의 개수
		int D = Integer.parseInt(st.nextToken());  //고속도로 길이


		// 인접 리스트 사용
		List<List<Node>> graph = new ArrayList<>();
		for (int i = 0; i <= D; i++) {
			graph.add(new ArrayList<>());  //삽입
		}

		// 고속도로의 기본 경로 추가
		for (int i = 0; i < D; i++) {
			graph.get(i).add(new Node(i + 1, 1));
		}

		// N개의 경로 입력
		for (int i = 0; i < N; i++) {
			st = new StringTokenizer(br.readLine());
			int x = Integer.parseInt(st.nextToken());  //시작
			int y = Integer.parseInt(st.nextToken());  //도착
			int length = Integer.parseInt(st.nextToken());  //지름길 길이(가중치)

			if (y <= D) {
				graph.get(x).add(new Node(y, length));  // x에서 y로 가는 간선
			}
		}

		// 최단 거리 저장 배열
		int[] dist = new int[D + 1];
		Arrays.fill(dist, Integer.MAX_VALUE);
		dist[0] = 0;  // 출발지의 거리 초기화

		// 우선순위 큐 사용
		PriorityQueue<Node> q = new PriorityQueue<>();
		q.add(new Node(0, 0));  //출발지 정점과 가중치를 우선순위 큐에 넣음

		// // 방문 여부를 체크할 배열
		// boolean[] visited = new boolean[N + 1];


		while (!q.isEmpty()) {  //큐에 값이 하나도 없을때까지 반복
			Node now = q.poll();  //큐에서 앞에 있는 노드 반환 및 삭제 (현재 큐에 있는 값 중 출발지로부터 가장 가까운 거리)
			int nowIdx = now.idx;

			// if (visited[nowIdx])  //방문했던 노드라면 패스
			// 	continue;
			// visited[nowIdx] = true;  //방문했다고 표시

			// 꺼낸 노드 = 현재 최소 비용을 갖는 노드.
			// 즉, 해당 노드의 비용이 현재 dist배열에 기록된 내용보다 크다면 고려할 필요가 없으므로 스킵한다.
			if (dist[nowIdx] < now.cost) {
				continue;//distance의 값이 더 작으니까 볼 필요없다 -> 이미 방문된 노드이다.
			}

			for (Node neighbor : graph.get(nowIdx)) {
				if (dist[neighbor.idx] > (dist[nowIdx] + neighbor.cost)) {
					dist[neighbor.idx] = dist[nowIdx] + neighbor.cost;
					q.add(new Node(neighbor.idx, dist[neighbor.idx]));
				}
			}
		}
		// 고속도로의 끝 위치까지의 최단 거리 출력
		System.out.println(dist[D]);
	}
}

 


주의할 점


고속도로의 길이가 주어졌고 지름길이 아니더라도 고속도로는 처음부터 끝까지 연결되어 있으므로 아래와 같이 설정

		// 인접 리스트 사용
		List<List<Node>> graph = new ArrayList<>();
		for (int i = 0; i <= D; i++) {
			graph.add(new ArrayList<>());  //삽입
		}

		// 고속도로의 기본 경로 추가
		for (int i = 0; i < D; i++) {
			graph.get(i).add(new Node(i + 1, 1));
		}
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.