05-18 01:37
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
Tags
- Mac
- Inheritance
- BFS
- 자바
- descriptive statistics
- Class
- X.org
- Polymolphism
- OOP
- Entity Set
- dbms
- selenium
- Java
- Operator
- Reference Type
- python
- systemd
- 리눅스
- External Scheme
- X윈도우
- spring
- preprocessing
- Binary Search
- 리눅스 마스터 1급
- 백준
- literal
- 셀레니움
- Entity
- Unity
- Physical Scheme
Archives
- Today
- Total
Byeol Lo
N1504 - 특정한 최단 경로 본문
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.StringTokenizer;
import java.util.HashMap;
import java.util.PriorityQueue;
import java.util.Arrays;
public class Main {
static final BufferedReader BR = new BufferedReader(new InputStreamReader(System.in));
static HashMap<Integer, HashMap<Integer, int[]>> graph;
static int[] dist1, dist2;
static StringTokenizer st;
static int n, m, v1, v2;
public static void main(String[] args) throws IOException {
input();
solution();
BR.close();
}
static void input() throws IOException {
int score;
st = new StringTokenizer(BR.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
graph = new HashMap<>(n);
dist1 = new int[n+1];
dist2 = new int[n+1];
Arrays.fill(dist1, Integer.MAX_VALUE);
Arrays.fill(dist2, Integer.MAX_VALUE);
for(int i=1; i<=n; i++)
graph.put(i, new HashMap<>());
for(int i=0; i<m; i++) {
st = new StringTokenizer(BR.readLine());
v1 = Integer.parseInt(st.nextToken());
v2 = Integer.parseInt(st.nextToken());
score = Integer.parseInt(st.nextToken());
graph.get(v1).put(v2, new int[]{v2, score});
graph.get(v2).put(v1, new int[]{v1, score});
}
st = new StringTokenizer(BR.readLine());
v1 = Integer.parseInt(st.nextToken());
v2 = Integer.parseInt(st.nextToken());
}
static void solution() {
int result;
dist1[v1] = 0;
dijkstra(v1, dist1);
dist2[v2] = 0;
dijkstra(v2, dist2);
result = Math.min(dist1[1] + dist2[n], dist1[n] + dist2[1]) + dist1[v2];
if(result >= 2e9 || result <= 0)
System.out.println(-1);
else
System.out.println(result);
}
static void dijkstra(int start, int[] dist) {
int[] curVer, nextVer;
PriorityQueue<int[]> path = new PriorityQueue<>(
(v1, v2)-> v1[1] - v2[1]
);
path.add(new int[]{start, dist[start]});
while(!path.isEmpty()) {
curVer = path.poll();
if(dist[curVer[0]] < curVer[1]) continue;
for(int key : graph.get(curVer[0]).keySet()) {
nextVer = graph.get(curVer[0]).get(key);
if(dist[nextVer[0]] > nextVer[1]+curVer[1]) {
dist[nextVer[0]] = nextVer[1]+curVer[1];
path.add(new int[]{nextVer[0], dist[nextVer[0]]});
}
}
}
}
}
'Algorithm > Dijkstra' 카테고리의 다른 글
N13549 - 숨바꼭질 3 (1) | 2024.01.14 |
---|---|
N1753 - 최단경로 (0) | 2023.12.27 |
N17396 - 백도어 (0) | 2023.12.24 |
Comments