Notice
Recent Posts
Recent Comments
Link
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

자르비 왕국

[백준] 1916 최소비용 구하기 - JAVA 본문

문제풀이

[백준] 1916 최소비용 구하기 - JAVA

자르비옹스 2022. 3. 13. 17:54

1. 문제 유형 : MST, 다익스트라

2. 시간복잡도 : O(ElogE)

  • O(E) : 모든 간선 탐색
  • O(logE) : 우선순위 큐의 연산
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

public class Main {

	static class Node {
		int v, weight;
		Node link;

		public Node(int v, int weight, Node link) {
			super();
			this.v = v;
			this.weight = weight;
			this.link = link;
		}
	}

	static class Vertex implements Comparable<Vertex> {
		int no, minDistance;

		public Vertex(int no, int minDistance) {
			super();
			this.no = no;
			this.minDistance = minDistance;
		}
		
		@Override
		public int compareTo(Vertex o) {
			return this.minDistance - o.minDistance;
		}
	}

	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		int N = Integer.parseInt(in.readLine());
		int M = Integer.parseInt(in.readLine());

		Node[] matrix = new Node[N + 1];
		StringTokenizer st = null;
		for (int i = 0; i < M; i++) {
			st = new StringTokenizer(in.readLine());
			int start = Integer.parseInt(st.nextToken());
			int end = Integer.parseInt(st.nextToken());
			int weight = Integer.parseInt(st.nextToken());
			matrix[start] = new Node(end, weight, matrix[start]);
		}

		st = new StringTokenizer(in.readLine());
		int from = Integer.parseInt(st.nextToken());
		int to = Integer.parseInt(st.nextToken());
		PriorityQueue<Vertex> pq = new PriorityQueue<>();
		boolean[] visited = new boolean[N + 1];
		int[] distance = new int[N + 1];
		Arrays.fill(distance, Integer.MAX_VALUE);
		
		pq.offer(new Vertex(from, 0));
		distance[from] = 0;

		while(!pq.isEmpty()) {
			Vertex v = pq.poll();
			if(visited[v.no]) continue;
			
			visited[v.no] = true;
			for (Node current=matrix[v.no]; current != null; current = current.link) {
				if(!visited[current.v] && distance[current.v] > distance[v.no]+current.weight) {
					distance[current.v] = distance[v.no]+current.weight;
					pq.offer(new Vertex(current.v, distance[current.v]));
				}
			}
			if(v.no == to) break;
		}
		
		System.out.println(distance[to]);
		
	}

}

'문제풀이' 카테고리의 다른 글

[백준] 2252 줄 세우기 - JAVA  (0) 2022.03.13
[백준] 1197 최소 스패닝 트리 - JAVA  (0) 2022.03.13
[백준] 1700 멀티탭 스케줄링 - JAVA  (0) 2022.03.12
[백준] 2578 빙고 - JAVA  (0) 2022.03.12
[BJ] 2564 경비원 - JAVA  (0) 2022.03.11