题目链接(测试数据弱化版):https://www.luogu.com.cn/problem/P3371
题目链接(测试数据强化版):https://www.luogu.com.cn/problem/P4779
import java.io.*;
import java.util.*;
class Edge implements Comparable<Edge> {
int to, w;
Edge() { to = w = 0; }
Edge(int m_to, int m_w) {
to = m_to;
w = m_w;
}
public int compareTo(Edge obj) {
return this.w - obj.w;
}
}
class Main {
static int INF = 0x7fffffff;
static int[] dis;
static boolean[] vis;
static ArrayList<Edge>[] G;
@SuppressWarnings("unchecked")
private static void Init(int n) {
dis = new int[n + 1];
vis = new boolean[n + 1];
G = new ArrayList[n + 1];
Arrays.fill(dis, INF);
Arrays.fill(vis, false);
for(int i = 0; i <= n; ++i) {
G[i] = new ArrayList<Edge>();
}
}
private static void Dijkstra(int s, int n) {
PriorityQueue<Edge> que = new PriorityQueue<Edge>();
que.add(new Edge(s, 0));
dis[s] = 0;
while(!que.isEmpty()) {
int u = que.poll().to;
if(vis[u] == true) continue;
vis[u] = true;
for(int i = 0; i < G[u].size(); ++i) {
Edge temp = G[u].get(i);
if(dis[temp.to] > dis[u] + temp.w) {
dis[temp.to] = dis[u] + temp.w;
que.add(new Edge(temp.to, dis[temp.to]));
}
}
}
}
public static void main(String[] args) throws IOException {
StreamTokenizer input = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
input.nextToken(); //将Scanner改成流输入,否则会超时或者超内存
int n = (int)input.nval;
input.nextToken();
int m = (int)input.nval;
input.nextToken();
int s = (int)input.nval;
Init(n);
for(int i = 1; i <= m; ++i) {
input.nextToken();
int u = (int)input.nval;
input.nextToken();
int v = (int)input.nval;
input.nextToken();
int w = (int)input.nval;
G[u].add(new Edge(v, w));
}
Dijkstra(s, n);
for(int i = 1; i <= n; ++i) {
System.out.print(dis[i] + " ");
}
}
}