模板题,考的是迪杰斯特拉,此题目还有一个加强版本
需要优化一下,才能通过。
请参照P4779 https://blog.youkuaiyun.com/mush_me/article/details/107026163
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
public class Main {
static Node4779[] lists;
static int[] len;
//说的是考迪杰斯特拉,实际考的是输入和输出,时间都卡在输入和输出上了
public static void main(String[] args) throws Exception{
/*BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer(reader.readLine());*/
StreamTokenizer st=new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
//StreamTokenizer st=new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
st.nextToken();
int n=(int)st.nval+1;//点的个数
st.nextToken();
int m=(int)st.nval;//有向边的个数
st.nextToken();
int s=(int)st.nval;//出发点的编号
lists=new Node4779[n];
len=new int[n];
for (int i = 0; i <lists.length ; i++) {
lists[i]=new Node4779();
}
//接下来 m 行每行包含三个整数 u,v,w,表示一条 u \to vu→v 的,长度为 ww 的边。
for (int i = 0; i <m ; i++) {
//st=new StringTokenizer(reader.readLine());
st.nextToken();
int start=(int)st.nval;
st.nextToken();
int to=(int)st.nval;
st.nextToken();
int dis=(int)st.nval;
lists[start].sonList.add(new int[]{to,dis});
}
processDS(lists,s);
StringBuilder ans = new StringBuilder();
for (int i = 1; i < n; i++) {
ans.append(lists[i].length).append(' ');
}
System.out.println(ans.toString());
//reader.close();
}
private static void processDS(Node4779[] nodes, int start) {
PriorityQueue<Node4779> pq=new PriorityQueue<Node4779>();
nodes[start].length=0;
nodes[start].visited=true;//加入队列
pq.add(nodes[start]);
while(!pq.isEmpty()){
Node4779 e=pq.poll();
if(!e.visited){//队列里有多个,已经出过队列一次了
continue;
}
e.visited=true;
for (int[] tolen:e.sonList) {//把e.to相连接的都加入进来
//这个点的路径 > 起点的路径 + 起点到当前点的距离
//tolen[0]是当前点的ID,tolen[1]是起点到当前点的距离
if(nodes[tolen[0]].length >e.length +tolen[1]){
nodes[tolen[0]].length =e.length +tolen[1];
nodes[tolen[0]].visited=true;
pq.add(nodes[tolen[0]]);
}
}
}
}
}
class Node4779 implements Comparable<Node4779>{
int index;//编号
boolean visited;//是否已经在队列中了
List<int[]> sonList;//保存这个节点的邻接节点 int[] [0]存放到达节点的编号 [1]存放到达节点的距离
int length;//保存起点到这个节点的距离
public Node4779() {
this.sonList=new ArrayList<int[]>();
this.length=Integer.MAX_VALUE;
}
@Override
public int compareTo(Node4779 o) {
return this.length-o.length;
}
}
本文深入探讨了迪杰斯特拉算法的应用与优化,通过一个模板题解析算法的实现细节,包括输入输出优化技巧,以及如何使用优先队列进行高效寻路。文章提供了一个Java实现的示例代码,展示了如何在有向图中找到从指定起点到其他所有点的最短路径。

被折叠的 条评论
为什么被折叠?



