在每年的校赛里,所有进入决赛的同学都会获得一件很漂亮的t-shirt。但是每当我们的工作人员把上百件的衣服从商店运回到赛场的时候,却是非常累的!所以现在他们想要寻找最短的从商店到赛场的路线,你可以帮助他们吗?
输入包括多组数据。每组数据第一行是两个整数N、M(N<=100,M<=10000),N表示成都的大街上有几个路口,标号为1的路口是商店所在地,标号为N的路口是赛场所在地,M则表示在成都有几条路。N=M=0表示输入结束。接下来M行,每行包括3个整数A,B,C(1<=A,B<=N,1<=C<=1000),表示在路口A与路口B之间有一条路,我们的工作人员需要C分钟的时间走过这条路。
输入保证至少存在1条商店到赛场的路线。
对于每组输入,输出一行,表示工作人员从商店走到赛场的最短时间
2 1 1 2 3 3 3 1 2 5 2 3 5 3 1 2 0 0
3 2
import java.util.*; public class Dijkstra{ static class Node{ int value; ArrayList<Node> nodes; ArrayList<Edge> edges; Node(int value){ this.value = value; nodes = new ArrayList<>(); edges = new ArrayList<>(); } @Override public String toString() { String res=value+":"; for(Node node:nodes){ res += node.value+" "; } res+="\n"; return res; } } static class Edge{ Node from; Node to; int cost; Edge(Node from,Node to,int cost){ this.from = from; this.to = to; this.cost = cost; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { int n = in.nextInt(); int m = in.nextInt(); if(n==0&&m==0){ break; } HashMap<Integer,Node> nodes = new HashMap<>(); HashSet<Edge> edges = new HashSet<>(); for(int i=1;i<=m;i++){ int from = in.nextInt(); int to = in.nextInt(); int cost = in.nextInt(); if(!nodes.containsKey(from)){ nodes.put(from,new Node(from)); } if(!nodes.containsKey(to)){ nodes.put(to,new Node(to)); } Node fromNode = nodes.get(from); Node toNode = nodes.get(to); Edge edge = new Edge(fromNode,toNode,cost); Edge edge2 = new Edge(toNode,fromNode,cost); fromNode.nodes.add(toNode); fromNode.edges.add(edge); fromNode.edges.add(edge2); toNode.nodes.add(fromNode); toNode.edges.add(edge); toNode.edges.add(edge2); } HashMap<Node,Integer> distanceMap = new HashMap<>(); HashSet<Node> selectedNodes = new HashSet<>(); Node head = nodes.get(1); distanceMap.put(head,0); Node minNode = getMinDistanceAndUnselectedNode(distanceMap,selectedNodes); while (minNode!=null){ int distance = distanceMap.get(minNode); for(Edge edge:minNode.edges){ Node toNode = edge.to; if(!distanceMap.containsKey(toNode)){ distanceMap.put(toNode,distance+edge.cost); } distanceMap.put(toNode,Math.min(distanceMap.get(toNode),distance+edge.cost)); } selectedNodes.add(minNode); minNode = getMinDistanceAndUnselectedNode(distanceMap,selectedNodes); } System.out.println(distanceMap.get(nodes.get(n))); } } private static Node getMinDistanceAndUnselectedNode( HashMap<Node, Integer> distanceMap, HashSet<Node> selectedNodes) { Node minNode = null; int minDistance = Integer.MAX_VALUE; for(Map.Entry<Node,Integer> entry:distanceMap.entrySet()){ Node node = entry.getKey(); int distance = entry.getValue(); if(!selectedNodes.contains(node)&&distance<minDistance){ minNode = node; minDistance = distance; } } return minNode; } }