Cod sursa(job #2220387)

Utilizator amimunAmelia Munteanu amimun Data 11 iulie 2018 16:25:43
Problema Floyd-Warshall/Roy-Floyd Scor 30
Compilator java Status done
Runda Arhiva educationala Marime 1.53 kb
import java.io.*;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        int n, i, j, k;

	    try {
            Scanner reader = new Scanner(new FileInputStream("royfloyd.in"));
            PrintWriter writer = new PrintWriter("royfloyd.out");
            n = reader.nextInt();
            int[][] a = new int[n+1][n+1];
            int[][] dist = new int[n+1][n+1];

            for (i = 1; i <= n; i++) {
                for (j = 1; j <= n; j++) {
                    a[i][j] = reader.nextInt();
                    if (a[i][j] == 0 && (i != j)) {
                        dist[i][j] = Integer.MAX_VALUE / 2;
                    } else if (i == j) {
                        dist[i][j] = 0;
                    } else {
                        dist[i][j] = a[i][j];
                    }
                }
            }

            for (k = 1; k <= n; k++) {
                for (i = 1; i <= n; i++) {
                    for (j = 1; j <= n; j++) {
                        if (dist[i][j] > dist[i][k] + dist[k][j])
                            dist[i][j] = dist[i][k] + dist[k][j];
                    }
                }
            }

            for (i = 1; i <= n; i++) {
                for (j = 1; j <= n; j++) {
                    writer.write(String.valueOf(dist[i][j]) + ((j != n ) ? " " : ""));
                }
                writer.println();
            }

            reader.close();
            writer.close();
        } catch (Exception e) {

        }
    }
}