最短路 JAVA
最短路很重要的一部分就是堆的实现,java也有自带的优先队列。
通过实现一个comparator的接口,来确定排序的优先级。
这里很重要的一个函数就是compare函数:和c++不同它返回的不是大小的判断,而是差值。
public int compare(int x, int y) { return x - y; }
若x < y则返回负值,x == y则返回0,x > y则返回正值。
默认情况下是升序即x - y的顺序,如果要降序就改成y - x即可。
对于存边的操作,通过List来实现即可(和c++里vector存边类似)
https://www.luogu.com.cn/problem/P4779
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import java.io.*; import java.util.*; public class Main { public static int N = 200005; public static long INF = Long.MAX_VALUE; static StreamTokenizer cin = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); static class Edge { int to,dis; Edge(int x,int y) { to = x; dis = y; } } static class Pair { int first; long second; Pair(int x,long y) { first = x; second = y; } } static List<Edge> edges[] = new List[N]; static int n,m,s; static long dis[] = new long[N]; static void solve() { PriorityQueue<Pair> Q = new PriorityQueue<>(new Comparator<Pair>() { @Override public int compare(Pair o1, Pair o2) { return (int) (o1.second - o2.second); } }); Arrays.fill(dis,Long.MAX_VALUE); dis[s] = 0; Q.add(new Pair(s,0)); while(!Q.isEmpty()) { Pair q = Q.poll(); if(dis[q.first] < q.second) continue; for(Edge v : edges[q.first]) { if(dis[v.to] > dis[q.first] + v.dis) { dis[v.to] = dis[q.first] + v.dis; Q.add(new Pair(v.to,dis[v.to])); } } } } public static void main(String[] args) throws IOException { cin.nextToken(); n = (int) cin.nval; cin.nextToken(); m = (int) cin.nval; cin.nextToken(); s = (int) cin.nval; for(int i = 1;i <= n;++i) edges[i] = new ArrayList<Edge>(); for(int i = 1;i <= m;++i) { cin.nextToken(); int u = (int) cin.nval; cin.nextToken(); int v = (int) cin.nval; cin.nextToken(); int w = (int) cin.nval; edges[u].add(new Edge(v,w)); } solve(); for(int i = 1;i <= n;++i) { out.print(dis[i] + " "); } out.close(); } }