AcWing 850. Dijkstra求最短路 II-java
原题链接
简单
作者:
硬拉tom
,
2020-08-14 19:12:02
,
所有人可见
,
阅读 436
import java.util.*;
class Main{
static int N=200010;
static int idx=0;
static int[] h=new int[N],e=new int[N],ne=new int[N],w=new int[N];
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
Arrays.fill(h,-1);
for(int i=0;i<m;i++){
add(sc.nextInt(),sc.nextInt(),sc.nextInt());
}
System.out.println(dij(n));
}
static void add(int from ,int to,int dist){//添加一条边
e[idx]=to;//出边指向to点
w[idx]=dist;//边距离
ne[idx]=h[from];//头插from点的邻接表
h[from]=idx++;
}
static int dij(int n){//n是点的数量
PriorityQueue<int[]> q=new PriorityQueue<int[]>(new Comparator<int[]>(){//小根堆
public int compare(int[] o1,int[] o2){
return o1[0]-o2[0];
}
});
q.offer(new int[]{0,1});// (距离,点编号)
boolean[] status=new boolean[n+1];//状态,表示下标编号的点已经求得到原点的最短距离
int[] dist=new int[n+1];//下标编号的点到原点最小距离
Arrays.fill(dist,0x3f3f3f3f);
dist[1]=0;
int[] cur;
int distance,point;
while(q.size()>0){
cur=q.poll();
distance=cur[0];
point=cur[1];
if(status[point]){
continue;
}
status[point]=true;
for(int i=h[point];i!=-1;i=ne[i]){
int j=e[i];
if(dist[j] > distance+w[i]){
dist[j]=distance+w[i];
q.offer(new int[]{dist[j],j});
}
}
}
return dist[n]==0x3f3f3f3f?-1:dist[n];
}
}