AcWing 851. [Java] spfa求最短路 yxc纯净版
原题链接
简单
作者:
莱昂纳多_达芬奇
,
2022-01-20 20:29:43
,
所有人可见
,
阅读 321
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
//只要没有负环就可以用。用的邻接表。
public class Main {
static int N = 100010;
static int n, m,idx;
static int[] h=new int[N];
static int[] w=new int[N];
static int[] e=new int[N];
static int[] ne=new int[N];
static int[] dist=new int[N];
static boolean[] st=new boolean[N];
private static void add(int a, int b, int c)
{
e[idx] = b; w[idx] = c; ne[idx] = h[a]; h[a] = idx ++ ;
}
private static int spfa()
{
Arrays.fill(dist,0x3f3f3f3f); //不能写成0x3f
dist[1] = 0;
Queue<Integer> q=new LinkedList<>();
q.offer(1);
st[1] = true;
while (q.size()>0)
{
int t = q.poll();
st[t] = false;
for (int i = h[t]; i != -1; i = ne[i])
{
int j = e[i];
if (dist[j] > dist[t] + w[i])
{
dist[j] = dist[t] + w[i];
if (!st[j])
{
q.offer(j);
st[j] = true;
}
}
}
}
return dist[n];
}
public static void main(String[] args) throws Exception{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s1[]=br.readLine().split(" ");
n=Integer.parseInt(s1[0]);
m=Integer.parseInt(s1[1]);
Arrays.fill(h, -1);
while (m -- >0)
{
int a, b, c;
s1=br.readLine().split(" "); //第二次用,不用加[ ]
a=Integer.parseInt(s1[0]);
b=Integer.parseInt(s1[1]);
c=Integer.parseInt(s1[2]);
add(a, b, c);
}
int t = spfa();
if (t == 0x3f3f3f3f) System.out.println("impossible");
else System.out.println(t);
}
}
......你为啥不直接把Queue的泛型改成Integer型呢,整这么麻烦干啥,转来转去的
当时不知道咋想的,已经改过来了,多谢提醒。