forked from rahulshetty09/ALGORITHMS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfloydwarshall.java
More file actions
55 lines (43 loc) · 1.22 KB
/
Copy pathfloydwarshall.java
File metadata and controls
55 lines (43 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class floydwarshall {
static Scanner sc = new Scanner(System.in);
static int i()
{
return sc.nextInt();
}
static final int max = Integer.MAX_VALUE/2-1;
public static void main(String[] args) {
int n = i();
int e = i();
int g[][] = new int[n+1][n+1];
for(int i=1;i<=n;i++)
Arrays.fill(g[i],max);
for(int i=0;i<e;i++)
g[i()][i()] = i();
for(int i=1;i<=n;i++)
g[i][i] = 0;
for(int k = 1;k<=n;k++)
{
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
if( g[i][j] > g[i][k] + g[k][j] )
g[i][j] = g[i][k] + g[k][j];
}
}
int q = i();
StringBuilder s = new StringBuilder();
for(int i=1;i<=q;i++)
{
int val = g[i()][i()];
if(val == max)
val = -1;
s.append(val+"\n");
}
System.out.print(s);
}
}