https://www.acmicpc.net/problem/1504
골드 4
방향성이 없는 그래프가 주어진다. 세준이는 1번 정점에서 N번 정점으로 최단 거리로 이동하려고 한다. 또한 세준이는 두 가지 조건을 만족하면서 이동하는 특정한 최단 경로를 구하고 싶은데, 그것은 바로 임의로 주어진 두 정점은 반드시 통과해야 한다는 것이다.
세준이는 한번 이동했던 정점은 물론, 한번 이동했던 간선도 다시 이동할 수 있다. 하지만 반드시 최단 경로로 이동해야 한다는 사실에 주의하라. 1번 정점에서 N번 정점으로 이동할 때, 주어진 두 정점을 반드시 거치면서 최단 경로로 이동하는 프로그램을 작성하시오.
첫째 줄에 정점의 개수 N과 간선의 개수 E가 주어진다. (2 ≤ N ≤ 800, 0 ≤ E ≤ 200,000) 둘째 줄부터 E개의 줄에 걸쳐서 세 개의 정수 a, b, c가 주어지는데, a번 정점에서 b번 정점까지 양방향 길이 존재하며, 그 거리가 c라는 뜻이다. (1 ≤ c ≤ 1,000) 다음 줄에는 반드시 거쳐야 하는 두 개의 서로 다른 정점 번호 v1과 v2가 주어진다. (v1 ≠ v2, v1 ≠ N, v2 ≠ 1) 임의의 두 정점 u와 v사이에는 간선이 최대 1개 존재한다.
첫째 줄에 두 개의 정점을 지나는 최단 경로의 길이를 출력한다. 그러한 경로가 없을 때에는 -1을 출력한다.
import java.util.*;
import java.io.*;
public class Main {
static int N, E;
static final int INF = 200000000;
static ArrayList<int[]>[] graph;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
E = Integer.parseInt(st.nextToken());
graph = new ArrayList[N + 1];
for(int i = 1; i <= N; i++) graph[i] = new ArrayList<>();
for(int i = 0; i < E; i++){
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
int c = Integer.parseInt(st.nextToken());
graph[a].add(new int[]{b, c});
graph[b].add(new int[]{a, c});
}
st = new StringTokenizer(br.readLine());
int v1 = Integer.parseInt(st.nextToken());
int v2 = Integer.parseInt(st.nextToken());
int[] distFrom1 = dijkstra(1);
int[] distFromV1 = dijkstra(v1);
int[] distFromV2 = dijkstra(v2);
long route1 = (long)distFrom1[v1] + distFromV1[v2] + distFromV2[N];
long route2 = (long)distFrom1[v2] + distFromV2[v1] + distFromV1[N];
long result = Math.min(route1, route2);
System.out.println(result >= INF ? -1 : result);
}
public static int[] dijkstra(int start){
int[] dist = new int[N + 1];
Arrays.fill(dist, INF);
dist[start] = 0;
PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[1]));
pq.add(new int[]{start, 0});
while(!pq.isEmpty()){
int[] now = pq.poll();
int node = now[0];
int cost = now[1];
if(dist[node] < cost) continue;
for(int[] next : graph[node]){
int nextNode = next[0];
int nextCost = next[1];
if(dist[nextNode] > cost + nextCost){
dist[nextNode] = cost + nextCost;
pq.add(new int[]{nextNode, dist[nextNode]});
}
}
}
return dist;
}
}
