結果
| 問題 |
No.160 最短経路のうち辞書順最小
|
| コンテスト | |
| ユーザー |
tenten
|
| 提出日時 | 2020-12-22 15:01:59 |
| 言語 | Java (openjdk 23) |
| 結果 |
AC
|
| 実行時間 | 628 ms / 5,000 ms |
| コード長 | 2,312 bytes |
| コンパイル時間 | 2,576 ms |
| コンパイル使用メモリ | 80,932 KB |
| 実行使用メモリ | 49,648 KB |
| 最終ジャッジ日時 | 2024-09-21 14:11:24 |
| 合計ジャッジ時間 | 12,133 ms |
|
ジャッジサーバーID (参考情報) |
judge4 / judge1 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 4 |
| other | AC * 26 |
ソースコード
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int start = sc.nextInt();
int goal = sc.nextInt();
ArrayList<TreeMap<Integer, Integer>> graph = new ArrayList<>();
for (int i = 0; i < n; i++) {
graph.add(new TreeMap<>());
}
for (int i = 0; i < m; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
graph.get(a).put(b, c);
graph.get(b).put(a, c);
}
PriorityQueue<Path> queue = new PriorityQueue<>();
queue.add(new Path(goal, 0));
int[] costs = new int[n];
Arrays.fill(costs, Integer.MAX_VALUE / 2);
while (queue.size() > 0) {
Path p = queue.poll();
if (costs[p.idx] <= p.value) {
continue;
}
costs[p.idx] = p.value;
for (Map.Entry<Integer, Integer> entry : graph.get(p.idx).entrySet()) {
queue.add(new Path(entry.getKey(), p.value + entry.getValue()));
}
}
int current = start;
int total = 0;
ArrayList<Integer> ans = new ArrayList<>();
ans.add(start);
while (current != goal) {
for (Map.Entry<Integer, Integer> entry : graph.get(current).entrySet()) {
if (costs[entry.getKey()] + total + entry.getValue() == costs[start]) {
total += entry.getValue();
current = entry.getKey();
ans.add(current);
break;
}
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ans.size(); i++) {
if (i > 0) {
sb.append(" ");
}
sb.append(ans.get(i));
}
System.out.println(sb);
}
static class Path implements Comparable<Path> {
int idx;
int value;
public Path(int idx, int value) {
this.idx = idx;
this.value = value;
}
public int compareTo(Path another) {
return value - another.value;
}
}
}
tenten