Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
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
Tags
more
Archives
Today
Total
관리 메뉴

코드와이

[BAEKJOON] 1916. 최소비용 구하기 본문

acmicpc

[BAEKJOON] 1916. 최소비용 구하기

코드와이 2021. 4. 12. 01:59

 

다익스트라

문제링크

www.acmicpc.net/problem/1916

 

1916번: 최소비용 구하기

첫째 줄에 도시의 개수 N(1 ≤ N ≤ 1,000)이 주어지고 둘째 줄에는 버스의 개수 M(1 ≤ M ≤ 100,000)이 주어진다. 그리고 셋째 줄부터 M+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그

www.acmicpc.net

 

package acmicpc.Gold5;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

public class 최소비용_구하기 {

static class Node implements Comparable<Node>{
		
		int to;
		int weight;
		
		public Node(int to, int weight) {
			super();
			this.to = to;
			this.weight = weight;
		}

		@Override
		public int compareTo(Node o) {
			
			return this.weight - o.weight;
		}
		
	}

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;
		
		int v = Integer.parseInt(br.readLine());
		int e = Integer.parseInt(br.readLine());
		
		ArrayList<Node>[] adjList = new ArrayList[v+1];
		
		for(int i = 0 ; i <= v ; i++) {
			adjList[i] = new ArrayList<Node>();
		}
		
		for(int i = 0 ; i < e ; i++) {
			st = new StringTokenizer(br.readLine());
			
			int f = Integer.parseInt(st.nextToken());
			int t = Integer.parseInt(st.nextToken());
			int w = Integer.parseInt(st.nextToken());
			
			adjList[f].add(new Node(t, w));
		}
		
		st = new StringTokenizer(br.readLine());
		
		int f = Integer.parseInt(st.nextToken());
		int t = Integer.parseInt(st.nextToken());
		
		int[] d = new int[v+1];
		Arrays.fill(d, Integer.MAX_VALUE);
		d[f] = 0;
		
		PriorityQueue<Node> pq = new PriorityQueue<Node>();
		pq.add(new Node(f,0));
		
		while(!pq.isEmpty()) {
			Node cur = pq.poll();
			if(cur.weight > d[cur.to]) {
				continue;
			}
			
			for(int i = 0 ; i < adjList[cur.to].size() ; i++) {
				Node n = adjList[cur.to].get(i);
				if( d[n.to] > cur.weight + n.weight) {
					d[n.to] = cur.weight + n.weight;
					pq.add(new Node(n.to, d[n.to]));
				}
			}
			
		}
		
		System.out.println(d[t]);
	}
}

'acmicpc' 카테고리의 다른 글

[BAEKJOON] 1238. 파티  (0) 2021.04.12
[BAEKJOON] 1261. 알고스팟  (0) 2021.04.12
[BAEKJOON] 10844. 쉬운 계단 수  (0) 2021.04.06
[BAEKJOON] 1912. 연속합  (0) 2021.04.05
[BAEKJOON] 1005. ACM Craft  (0) 2021.04.05