What is Floyd?
The Floyd algorithm, also known as the interpolation method, is an algorithm that uses the idea of dynamic programming to find the shortest path between multiple source points in a given weighted graph, similar to the Dijkstra algorithm.
Now we use it.
Like Dynamic programming ,d[i][j] is the shortest distance between i and j.
Updating : d[i][j] = min(d[i][j], d[i][k] + d[k][j])
private static void Floyd() {
for (int k = 1; k <= n; k++)
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
d[i][j] = Math.min(d[i][j], d[i][k] + d[k][j]);
}
And the problem.
Problem in AcWing
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(System.out);
static int N = 207;
static long d[][] = new long[N][N];
static int n, m, q;
public static void main(String[] srga) throws IOException {
String s[] = br.readLine().split(" ");
n = Integer.parseInt(s[0]);
m = Integer.parseInt(s[1]);
q = Integer.parseInt(s[2]);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
if (i == j) d[i][j] = 0;
else d[i][j] = Integer.MAX_VALUE;
for (int i = 0; i < m; i++) {
s = br.readLine().split(" ");
int a = Integer.parseInt(s[0]);
int b = Integer.parseInt(s[1]);
int c = Integer.parseInt(s[2]);
d[a][b] = Math.min(d[a][b], c);
}
Floyd();
for (int i = 0; i < q; i++) {
s = br.readLine().split(" ");
int a = Integer.parseInt(s[0]);
int b = Integer.parseInt(s[1]);
if (d[a][b] >= (Integer.MAX_VALUE >> 1)) pw.println("impossible");
else pw.println(d[a][b]);
}
pw.flush();
br.close();
}
private static void Floyd() {
for (int k = 1; k <= n; k++)
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
d[i][j] = Math.min(d[i][j], d[i][k] + d[k][j]);
}
}