AcWing 854. Floyd求最短路-java
原题链接
简单
作者:
Astarion
,
2021-02-15 17:01:33
,
所有人可见
,
阅读 238
import java.io.*;
import java.util.Arrays;
class Main {
static final int INF = 0x3fffffff;
//邻接矩阵存储
//Floyd算法只需开一个邻接矩阵,原地操作
static int[][] g = new int[210][210];
static {
for (int i = 0; i < 210; i++) {
Arrays.fill(g[i], INF);
}
}
static int n, m, k;
static void insert(int a, int b, int v) {
g[a][b] = Math.min(g[a][b], v);
}
static void floyd() {
for (int k = 1; k <= n; k++)
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
g[i][j] = Math.min(g[i][j], g[i][k] + g[k][j]);
}
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
String[] strs = in.readLine().split(" ");
n = Integer.parseInt(strs[0]);
m = Integer.parseInt(strs[1]);
k = Integer.parseInt(strs[2]);
for (int i = 1; i <= n; i++) g[i][i] = 0;
for (int i = 0; i < m; i++) {
strs = in.readLine().split(" ");
int a = Integer.parseInt(strs[0]);
int b = Integer.parseInt(strs[1]);
int v = Integer.parseInt(strs[2]);
insert(a, b, v);
}
OutputStreamWriter osw = new OutputStreamWriter(System.out);
BufferedWriter out = new BufferedWriter(osw);
floyd();
for (int i = 0; i < k; i++) {
strs = in.readLine().split(" ");
int a = Integer.parseInt(strs[0]);
int b = Integer.parseInt(strs[1]);
if (g[a][b] > INF / 2) out.write("impossible\n");
else out.write(g[a][b] + "\n");
}
in.close();
isr.close();
out.flush();
out.close();
osw.close();
}
}