Resource Limits
Time Limit: 1.0s Memory Limit: 256.0MB
Problem Description
Given a directed graph with n vertices and m edges (where some edge weights may be negative, but no negative cycles are guaranteed). Please calculate the shortest path from point 1 to other points (vertices are numbered from 1 to n).
Input format
Two integers n, m in the first line.
The next m lines, each with three integers u, v, l, indicate that there is an edge of length l from u to v.
Output format
A total of n-1 lines, the i-th line represents the shortest path from point 1 to point i+1.
Sample input
3 3
1 2 -1
2 3 -1
3 1 2
Sample output
-1
-2
Data size and convention
For 10% of the data, n = 2, m = 2.
For 30% of the data, n <= 5, m <= 10.
For 100% of the data, 1 <= n <= 20000, 1 <= m <= 200000, -10000 <= l <= 10000, guaranteeing that any vertex can be reached from all other vertices.
———————————————————————————————————————————————————
——Have negative edge weight, use spfa, there is more data, use fast read and fast write
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
public class Main {
static int N = 20010, M = 200010;
static int INF = Integer.MAX_VALUE >> 1;
static int[] h = new int[N];
static int[] e = new int[M];
static int[] ne = new int[M];
static int[] w = new int[M];
static int idx;
static int[] dist = new int[N];
static boolean[] st = new boolean[N];
static int n;
static int m;
static PrintWriter pw = new PrintWriter(System.out);
public static void main(String[] args) throws IOException {
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);
for (int i = 0; i < m; i++) {
String[] s2 = br.readLine().split(" ");
int a = Integer.parseInt(s2[0]);
int b = Integer.parseInt(s2[1]);
int c = Integer.parseInt(s2[2]);
add(a, b,c);
}
spfa();
}
private static void spfa() {
Arrays.fill(dist, INF);
dist[1] = 0;
Queue<Integer> q = new LinkedList<Integer>();
q.add(1);
st[1] = true;
while (!q.isEmpty()) {
Integer 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.add(j);
st[j] = true;
}
}
}
}
for (int i = 2; i <= n; i++) {
pw.println(dist[i]);
}
pw.flush();
}
private static void add(int a, int b, int c) {
e[idx] = b;
w[idx] = c;
ne[idx] = h[a];
h[a] = idx++;
}
}