JAVA Dijkstra最短路 优先队列优化模板 HDU2544

最近备战蓝桥杯,被蛊惑报了JAVA组,送了波经验,但是也写了些比较有趣的代码。今天先和大家分享一下自己写的JAVA版Dijkstra 最短路堆优化版代码。

本代码采用了邻接表(List)的方式定义图,并且在HDU2544上正确AC

import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        while (true) {
            int n = cin.nextInt(), m = cin.nextInt();
            if(n==0&m==0)break;
            List> vec = new ArrayList<>();
            for (int i = 0; i < n + 5; i++) {
                vec.add(new ArrayList<>());
            }
            int dis[] = new int[n + 5];
            boolean vis[] = new boolean[n + 5];
            for (int i = 0; i < m; i++) {
                int a = cin.nextInt(), b = cin.nextInt(), c = cin.nextInt();
                vec.get(a).add(new Edge(b, c));
                vec.get(b).add(new Edge(a,c));
            }
            for (int i = 0; i <= n; i++) {
                dis[i] = Integer.MAX_VALUE;
                vis[i] = false;
            }
            dis[1] = 0;
            PriorityQueue queue = new PriorityQueue<>();
            queue.add(new Node(1, 0));
            while (!queue.isEmpty()) {
                Node now = queue.poll();
                if (vis[now.point]) {
                    continue;
                }
                vis[now.point] = true;
                for (int i = 0; i < vec.get(now.point).size(); i++) {
                    Edge nxt = vec.get(now.point).get(i);
                    if (nxt.val + dis[now.point] < dis[nxt.to]) {
                        dis[nxt.to] = nxt.val + dis[now.point];
                        queue.add(new Node(nxt.to, dis[nxt.to]));
                    }
                }
            }
            System.out.println(dis[n]);
        }
    }
}
class Edge{
    int to,val;
    public Edge(int to,int val){
        this.to=to;
        this.val=val;
    }
}
class Node implements Comparable{
    int point,val;
    public Node(int point,int val){
        this.val=val;
        this.point=point;
    }
    @Override
    public int compareTo(Node node){
        return  val-node.val;
    }
}

 

你可能感兴趣的:(ACM代码,HDU,ACM,JAVA,最短路)