Home BOJ. Floyd (11404)
Post
Cancel

BOJ. Floyd (11404)

[Link] https://www.acmicpc.net/problem/11404


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
import java.util.*;
import java.io.*;

public class Main {
	static BufferedReader br;
	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		String[] line;
		int n = toi(br.readLine()), m = toi(br.readLine());
		int[][] dis = new int[n][n];
		int[][] floyd = new int[n][n];
		boolean[][] visit = new boolean[n][n];

		for(int i = 0; i < m; i++) {
			line = getLine();
			int a = toi(line[0]) - 1, b = toi(line[1]) - 1, c = toi(line[2]);
			if(!visit[a][b]) {
				dis[a][b] =  floyd[a][b] = c;
				visit[a][b] = true;
			} else dis[a][b] =  floyd[a][b] = Math.min(dis[a][b], c);
		}
		for(int i = 0; i < n; i++) visit[i][i] = true;

		for(int mid = 0; mid < n; mid++) {
			for(int from = 0; from < n; from++) {
				for(int to = 0; to < n; to++) {
					if(visit[from][mid] && visit[mid][to]) {
						if(!visit[from][to]) {
							floyd[from][to] = floyd[from][mid] + floyd[mid][to];
							visit[from][to] = true;
						}
						else floyd[from][to] = Math.min(floyd[from][to], floyd[from][mid] + floyd[mid][to]);
					}
				}
			}
		}
		for(int[] ar: floyd) {
			for(int e: ar) sb.append(e + " ");
			sb.setLength(sb.length() - 1);
			sb.append("\n");
		}
		print(sb);
	}

	static int toi(String s) { return Integer.parseInt(s); }
	static String[] getLine() throws IOException { return br.readLine().split(" "); }
	static <T> void print(T s) { System.out.print(s); }
	static <T> void println(T s) { System.out.println(s); }
}
This post is licensed under CC BY 4.0 by the author.