結果
| 問題 |
No.160 最短経路のうち辞書順最小
|
| コンテスト | |
| ユーザー |
htensai
|
| 提出日時 | 2020-01-15 19:07:31 |
| 言語 | Java (openjdk 23) |
| 結果 |
AC
|
| 実行時間 | 612 ms / 5,000 ms |
| コード長 | 2,582 bytes |
| コンパイル時間 | 1,958 ms |
| コンパイル使用メモリ | 79,932 KB |
| 実行使用メモリ | 80,780 KB |
| 最終ジャッジ日時 | 2024-06-11 16:21:58 |
| 合計ジャッジ時間 | 10,128 ms |
|
ジャッジサーバーID (参考情報) |
judge4 / judge5 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 4 |
| other | AC * 26 |
ソースコード
import java.util.*;
import java.math.*;
public class Main {
static int[] base;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int s = sc.nextInt();
int g = sc.nextInt();
ArrayList<Path>[] graph = new ArrayList[n];
for (int i = 0; i < n; i++) {
graph[i] = new ArrayList<Path>();
}
for (int i = 0; i < m; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
graph[a].add(new Path(b, c));
graph[b].add(new Path(a, c));
}
PriorityQueue<Route> queue = new PriorityQueue<>();
ArrayList<Integer> list = new ArrayList<>();
list.add(s);
queue.add(new Route(s, 0, list));
Route[] routes = new Route[n];
while (queue.size() > 0) {
Route r = queue.poll();
if (routes[r.to] != null) {
continue;
}
routes[r.to] = r;
for (Path p : graph[r.to]) {
ArrayList<Integer> newList = new ArrayList<>(r.name);
newList.add(p.to);
queue.add(new Route(p.to, r.score + p.score, newList));
}
}
StringBuilder sbr = new StringBuilder();
for (int i = 0; i < routes[g].name.size(); i++) {
if (i != 0) {
sbr.append(" ");
}
sbr.append(routes[g].name.get(i));
}
System.out.println(sbr);
}
static class Route implements Comparable<Route> {
int to;
int score;
ArrayList<Integer> name;
public Route (int to, int score, ArrayList<Integer> name) {
this.to = to;
this.score = score;
this.name = name;
}
public int compareTo(Route another) {
if (score == another.score) {
for (int i = 0; i < name.size() && i < another.name.size(); i++) {
if (name.get(i) != another.name.get(i)) {
return name.get(i) - another.name.get(i);
}
}
return name.size() - another.name.size();
} else {
return score - another.score;
}
}
}
static class Path {
int to;
int score;
public Path(int to, int score) {
this.to = to;
this.score = score;
}
}
}
htensai