๋ฌธ์ 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]);
}
}
}
'๐ ์๊ณ ๋ฆฌ์ฆ > ShortestPath' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode] 1091. Shortest Path in Binary Matrix (ํด์, Kotlin ํ์ด) (0) | 2023.06.19 |
---|---|
[๋ฐฑ์ค] 13549๋ฒ: ์จ๋ฐ๊ผญ์ง3 (0) | 2022.04.03 |
[๋ฐฑ์ค] 1238๋ฒ: ํํฐ (JAVA) (0) | 2022.04.03 |
[๋ฐฑ์ค]11780๋ฒ ํ๋ก์ด๋2 (Java) (0) | 2022.02.21 |
[๋ฐฑ์ค] 16118๋ฒ ๋ฌ๋น์ฌ์ฐ (Java) (0) | 2022.02.08 |