1 条题解
-
0
java ac代码:
import java.util.*; import java.util.StringTokenizer; import java.io.*; public class Main { static int n,m;//n为节点数,m为边数 static long[] d;//d[i]代表第i个节点到原点的最小距离 static List<int[]>[] list;//邻接表,int[]中两个参数{v,w};v表示连接的边,w表示边权 //优先队列q,long[]中两个参数{d,i};i为节点名,d为i节点到原点的距离 static PriorityQueue<long[]> q=new PriorityQueue<>((o1,o2)->Long.compare(o1[0],o2[0])); public static void main(String[] args) { //数据读入 n=in.nextInt(); m=in.nextInt(); //初始化邻接表和数组 d=new long[n+1]; d[1]=0;//原点到自身的距离为0 list=new List[n+1]; for(int i=1;i<=n;i++) list[i]=new ArrayList<>(); /*默认刚开始的时候都达不到原点(没有边) 将距离设置为最大,不干扰下面优先队列的判断 */ Arrays.fill(d,Long.MAX_VALUE); //数据读入 while(m-->0) { int u=in.nextInt(),v=in.nextInt(),w=in.nextInt(); if(u==v) continue;//自环的时候不添加,少遍历 list[u].add(new int[] {v,w});//有向边,只用加一次 } //初始化优先队列 q.add(new long[] {0,1});//原点到自身的距离为0 while(!q.isEmpty()) { long[] temp=q.poll();//弹出第一个值(现在离原点最近的值) long distance=temp[0];//该点到原点的距离 long index=temp[1];//第index个节点 for(int[] a:list[(int) index]) { int index_a=a[0];//index节点可以走向的节点 int distance_a=a[1];//index节点走向这个节点的距离 //如果原点经过index节点(中间点)到index_a节点的距离 //比之前的d[index_a]小的话就更新d[index_a] if(distance+distance_a<d[index_a]) { d[index_a]=distance+distance_a; q.add(new long[] {d[index_a],index_a});//将index_a入队 //(原点到index_a的最小路径) } } } out.println(d[n]==Long.MAX_VALUE?-1:d[n]); out.close(); } static FastReader in=new FastReader(); static PrintWriter out=new PrintWriter(System.out); static class FastReader{ static BufferedReader br; static StringTokenizer st; FastReader(){ br=new BufferedReader(new InputStreamReader(System.in)); } String next() { String str=""; while(st==null||!st.hasMoreElements()) { try { str=br.readLine(); }catch(IOException e) { throw new RuntimeException(e); } st=new StringTokenizer(str); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } } }
- 1
信息
- ID
- 27
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 4
- 标签
- 递交数
- 27
- 已通过
- 12
- 上传者