๐Ÿ“ ์•Œ๊ณ ๋ฆฌ์ฆ˜/ShortestPath

[๋ฐฑ์ค€] 1753๋ฒˆ ์ตœ๋‹จ๊ฒฝ๋กœ (Java)

์ ์ด 2021. 8. 24. 20:38
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ Gold5

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

 

1753๋ฒˆ: ์ตœ๋‹จ๊ฒฝ๋กœ

์ฒซ์งธ ์ค„์— ์ •์ ์˜ ๊ฐœ์ˆ˜ V์™€ ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜ E๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. (1≤V≤20,000, 1≤E≤300,000) ๋ชจ๋“  ์ •์ ์—๋Š” 1๋ถ€ํ„ฐ V๊นŒ์ง€ ๋ฒˆํ˜ธ๊ฐ€ ๋งค๊ฒจ์ ธ ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•œ๋‹ค. ๋‘˜์งธ ์ค„์—๋Š” ์‹œ์ž‘ ์ •์ ์˜ ๋ฒˆํ˜ธ K(1≤K≤V)๊ฐ€ ์ฃผ์–ด์ง„๋‹ค.

www.acmicpc.net


ํ’€์ด

์‹œ์ž‘์ ์—์„œ ๋ชจ๋“  ์ •์ ๊นŒ์ง€์˜ ์ตœ๋‹จ๊ฒฝ๋กœ๋ฅผ ๊ตฌํ•˜๋Š” ๋‹ค์ต์ŠคํŠธ๋ผ(Dijkstra) ์•Œ๊ณ ๋ฆฌ์ฆ˜

๋‹ค์ต์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ตฌํ˜„

- ์‹œ์ž‘์ ์—์„œ๋ถ€ํ„ฐ ๋ฐฉ๋ฌธ์—ฌ๋ถ€์™€ ์‹œ์ž‘์ ๋ถ€ํ„ฐ์˜ ์ตœ์†Œ ๊ฒฝ๋กœ ์ •์ ์„ ํƒ์ƒ‰

- ์ตœ์†Œ ๊ฒฝ๋กœ ์ •์  ํƒ์ƒ‰ ํ›„, ํ•ด๋‹น ์ •์ ์— ๋Œ€ํ•œ distance๋ฐฐ์—ด(ํ•ด๋‹น ์ •์ ์„ ๊ฒฝ์œ ํ•ด์„œ ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ์ตœ๋‹จ ๊ฑฐ๋ฆฌ)์„ ์žฌ์„ค์ •

 

๊ทธ๋ž˜ํ”„ ์ •๋ณด๋ฅผ ์ฒ˜์Œ ์ธ์ ‘ํ–‰๋ ฌ๋กœ ํ’€์—ˆ์œผ๋‚˜ ํ…Œ์ผ€์˜ ํฌ๊ธฐ๊ฐ€ ๋งค์šฐ ํฌ๊ธฐ ๋•Œ๋ฌธ์— ๋ฉ”๋ชจ๋ฆฌ ์ดˆ๊ณผ ์˜ค๋ฅ˜๊ฐ€ ๋‚ฌ๋‹ค.

๋”ฐ๋ผ์„œ ์ด๋ฅผ ์ธ์ ‘ ํ–‰๋ ฌ์ด ์•„๋‹Œ ์ธ์ ‘ ๋ฆฌ์ŠคํŠธ๋กœ ๊ตฌํ˜„ํ•˜์˜€๋‹ค.

 

์ฝ”๋“œ

๋”๋ณด๊ธฐ
import java.util.*;
import java.io.*;

class Element{
	int to, weight;
	public Element(int to, int weight) {
		this.to = to;
		this.weight = weight;
	}
}
public class Main{
	public static void main(String[] args) throws Exception{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine(), " ");
		int V = Integer.parseInt(st.nextToken());
		int E = Integer.parseInt(st.nextToken());
		int K = Integer.parseInt(br.readLine());
		
		List<Element>[] adjList = new ArrayList[V+1];
		for(int i =1 ; i < V+1 ; i++) {
			adjList[i] = new ArrayList<>();
		}
		int[] distance = new int[V+1];
		boolean[] visited = new boolean[V+1];
		
		for(int i = 0 ; i < E ; i++) {
			st = new StringTokenizer(br.readLine(), " ");
			int from = Integer.parseInt(st.nextToken());
			int to = Integer.parseInt(st.nextToken());
			int weight = Integer.parseInt(st.nextToken());
			adjList[from].add(new Element(to, weight));
		}
		
		Arrays.fill(distance, Integer.MAX_VALUE);
		distance[K] = 0;
		
		int min = 0, current = 1;
		for(int i =1 ; i <= V ; i++) {
			min = Integer.MAX_VALUE;
			for(int j =1  ; j <= V ; j++) {
				if(!visited[j] && distance[j] < min) {
					min = distance[j];
					current = j;
				}
			}
			visited[current] = true;
			for(int j =0 ; j < adjList[current].size() ; j++) {
				if(!visited[adjList[current].get(j).to] && distance[adjList[current].get(j).to] > min+adjList[current].get(j).weight) {
					distance[adjList[current].get(j).to] = min+adjList[current].get(j).weight;
				}
			}
		}
		
		for(int i = 1; i <= V ; i++) {
			if(distance[i] == Integer.MAX_VALUE) System.out.println("INF");
			else System.out.println(distance[i]);
		}
	}
}
๋ฐ˜์‘ํ˜•