https://www.acmicpc.net/problem/2307
2307번: 도로검문
그림 1은 어떤 도시의 주요 지점과 그 지점들 간의 이동시간을 나타낸 그래프이다. 그래프의 노드는 주요 지점을 나타내고 두 지점을 연결한 도로(에지)에 표시된 수는 그 도로로 이동할 때 걸
www.acmicpc.net
[문제]
[풀이]
1. 다익스트라를 돌려서 N번 노드까지의 최단거리를 구하고 , 경로를 구한다.
2. 구한 경로의 edge를 하나씩 빼면서 다익스트라를 경로의 수 만큼 다시 돌린다.
3. 늘어난 시간 중 가장 긴 거리와 1번에서 구한 최단거리의 차이를 반환하면 끝.
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
import java.util.*;
import java.io.*;
import java.util.stream.Collectors;
public class Main {
static int N,M;
static ArrayList<int[]>[] list;
static int[] distance,path;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[] input = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
N = input[0]; M = input[1];
init();
for(int i=0;i<M;i++){
input = Arrays.stream(br.readLine().split(" "))
.mapToInt(Integer::parseInt).toArray();
list[input[0]].add(new int[]{input[1], input[2]});
list[input[1]].add(new int[]{input[0], input[2]});
}
path = new int[N+1];
Arrays.fill(path,-1);
int shortPath = findShortestPath();
int maxPath = 0;
for(int i=N;i>0;i=path[i])
maxPath = Math.max(maxPath,otherPath(path[i],i));
if(maxPath==Integer.MAX_VALUE) System.out.println(-1);
else System.out.println(maxPath-shortPath);
}
private static int findShortestPath() {
Arrays.fill(distance,Integer.MAX_VALUE);
distance[1]=0;
Queue<int[]> q = new PriorityQueue<>((o1, o2) -> o1[1]-o2[1]);
q.add(new int[]{1, 0});
while (!q.isEmpty()){
int[] cur = q.poll();
if(cur[1] > distance[cur[0]]) continue;
for (int[] next : list[cur[0]]) {
if(distance[next[0]] > distance[cur[0]]+next[1]){
distance[next[0]] = distance[cur[0]]+next[1];
q.add(new int[]{next[0],distance[next[0]]});
path[next[0]] = cur[0];
}
}
}
return distance[N];
}
private static int otherPath(int from,int to) {
Arrays.fill(distance,Integer.MAX_VALUE);
distance[1]=0;
Queue<int[]> q = new PriorityQueue<>((o1, o2) -> o1[1]-o2[1]);
q.add(new int[]{1, 0});
while (!q.isEmpty()){
int[] cur = q.poll();
if(cur[1] > distance[cur[0]]) continue;
for (int[] next : list[cur[0]]) {
if(from == cur[0] && to==next[0]) continue;
if(distance[next[0]] > distance[cur[0]]+next[1]){
distance[next[0]] = distance[cur[0]]+next[1];
q.add(new int[]{next[0],distance[next[0]]});
}
}
}
return distance[N];
}
private static void init() {
list = new ArrayList[N+1];
for(int i=1;i<=N;i++) list[i]= new ArrayList<>();
distance = new int[N+1];
}
}
|
cs |
'알고리즘,PS > 백준' 카테고리의 다른 글
[BOJ] 백준 [1135] 뉴스 전하기 JAVA (0) | 2021.11.08 |
---|---|
[BOJ] 백준 [3055] 탈출 JAVA (0) | 2021.11.07 |
[BOJ] 백준 [1781] 컵라면 JAVA (0) | 2021.11.02 |
[BOJ] 백준 [1461] 도서관 JAVA (0) | 2021.11.01 |
[BOJ] 백준 [11400] 단절선 JAVA (0) | 2021.10.31 |