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

출발지 노드 배열 -> 도착지 노드 배열로 가는 최단거리의 합을 구하는 문제이다.
출발지 노드배열 요소 개수만큼 다익스트라를 돌려 도착지 노드들까지의 거리를 합하고, 도달 불가능한 경우 -1로 치환해 합했다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[] info = getArray(br.readLine());
int startCount = info[0];
int nodeCount = info[1];
int roadCount = info[2];
int[] end = getArray(br.readLine());
int[] startArr = getArray(br.readLine());
List<List<P12834>> list = new ArrayList<>();
for (int i = 0; i <= nodeCount; i++) {
list.add(new ArrayList<>());
}
int[][] dist = new int[startCount][nodeCount + 1];
for (int i = 0; i < roadCount; i++) {
int[] v = getArray(br.readLine());
list.get(v[0]).add(new P12834(v[1], v[2]));
list.get(v[1]).add(new P12834(v[0], v[2]));
}
PriorityQueue<P12834> pq = new PriorityQueue<>();
for (int i = 0; i < startCount; i++) {
Arrays.fill(dist[i], Integer.MAX_VALUE);
P12834 start = new P12834(startArr[i], 0);
dist[i][startArr[i]] = 0;
pq.offer(start);
while (!pq.isEmpty()) {
P12834 poll = pq.poll();
int value = poll.to;
int cost = poll.weight;
if (cost < dist[i][value]) continue;
List<P12834> rList = list.get(value);
for (int j = 0; j < rList.size(); j++) {
P12834 road = rList.get(j);
if (cost + road.weight < dist[i][road.to]) {
dist[i][road.to] = cost + road.weight;
P12834 offer = new P12834(road.to, cost + road.weight);
pq.offer(offer);
}
}
}
}
int sum = 0;
for (int i = 0; i < startCount; i++) {
for (int j = 0; j < end.length; j++) {
sum+=dist[i][end[j]]==Integer.MAX_VALUE?-1:dist[i][end[j]];
}
}
System.out.println(sum);
}
static int par(String s) {
return Integer.parseInt(s);
}
static int[] getArray(String s) {
return Arrays.stream(s.split(" ")).mapToInt(Integer::parseInt).toArray();
}
}
class P12834 implements Comparable<P12834> {
int to;
int weight;
P12834(int t, int weight) {
this.to = t;
this.weight = weight;
}
@Override
public int compareTo(P12834 o) {
return this.weight - o.weight;
}
}'백준' 카테고리의 다른 글
| [JAVA] 백준 14497 - 주난의 난(難) (0) | 2025.10.08 |
|---|---|
| [JAVA] 백준 13424 - 비밀 모임 (0) | 2025.10.08 |
| [JAVA] 백준 12441, 12442 - 약속장소 정하기(Small, Large) (0) | 2025.10.07 |
| [JAVA] 백준 10282 - 해킹 (0) | 2025.10.06 |
| [JAVA] 백준 20168 - 골목 대장 호석 - 기능성 (0) | 2025.10.05 |