結果
| 問題 |
No.160 最短経路のうち辞書順最小
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2016-05-01 12:26:37 |
| 言語 | Java (openjdk 23) |
| 結果 |
AC
|
| 実行時間 | 525 ms / 5,000 ms |
| コード長 | 2,520 bytes |
| コンパイル時間 | 2,110 ms |
| コンパイル使用メモリ | 90,080 KB |
| 実行使用メモリ | 54,940 KB |
| 最終ジャッジ日時 | 2024-10-05 00:33:01 |
| 合計ジャッジ時間 | 10,987 ms |
|
ジャッジサーバーID (参考情報) |
judge3 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 4 |
| other | AC * 26 |
ソースコード
package yukicoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Scanner;
public class Main{
public static void main(String[] args)throws Exception{
new Main().solve();
}
void solve(){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
int s=sc.nextInt();
int g=sc.nextInt();
Dijkstra dj=new Dijkstra(n);
for(int i=0;i<m;i++){
int from=sc.nextInt();
int to=sc.nextInt();
int cost=sc.nextInt();
dj.addEdge(from, to, cost);
dj.addEdge(to, from, cost);
}
int[] prv=dj.getShortestPath(g, s);
String ans="";
ans+=s;
int f=s;
while(true){
int a=prv[f];
f=a;
if(f!=-1){
ans=ans+" "+a;
if(a==g)break;
}
}
System.out.println(ans);
// tr(prv);
}
void tr(Object...o){System.out.println(Arrays.deepToString(o));}
class Dijkstra{
int n;
long[] d;
int s;
int[] prv;
List<Edge>[]edges;
PriorityQueue<Vertice> pq;
final long INF=Long.MAX_VALUE/4;
Dijkstra(int n){
this.n=n;
d=new long[n];
prv=new int[n];
Arrays.fill(prv, -1);
@SuppressWarnings("unchecked")
List<Edge>[]edges=new List[n];
this.edges=edges;
for(int i=0;i<n;i++){
edges[i]=new ArrayList<Edge>();
}
s=-1;
}
int[] getShortestPath(int i,int j){
if(i!=s){
s=i;
Arrays.fill(d, INF);
d[i]=0;
pq=new PriorityQueue<Vertice>();
pq.add(new Vertice(i,d[i]));
while(!pq.isEmpty()){
Vertice u=pq.poll();
if(d[u.me]<u.cost){
continue;//skip old vertex
}
for(int ii=0;ii<edges[u.me].size();ii++){
Edge e=edges[u.me].get(ii);
if(d[e.from]!=INF&&e.cost+d[e.from]<d[e.to]){
d[e.to]=e.cost+d[e.from];
pq.add(new Vertice(e.to,d[e.to]));
prv[e.to]=e.from;
}else if(d[e.to]==e.cost+d[e.from]&&prv[e.to]>e.from){
prv[e.to]=e.from;
}
}
}
s=i;
}
// return d[j];
return prv;
}
void addEdge(int from,int to,long cost){
edges[from].add(new Edge(from,to,cost));
}
}
class Edge{
int from;
int to;
long cost;
Edge(int i,int j,long cost){
this.from=i;
this.to=j;
this.cost=cost;
}
}
class Vertice implements Comparable<Vertice>{
int me;
long cost;
Vertice(int me,long cost){
this.me=me;
this.cost=cost;
}
@Override
public int compareTo(Vertice o){
// return Long.compare(this.cost, o.cost);
return this.cost>o.cost?1:this.cost<o.cost?-1:this.me>o.me?1:this.me<o.me?-1:0;
}
}
}