Cod sursa(job #352605)

Utilizator slayerdmeMihai Dumitrescu slayerdme Data 2 octombrie 2009 17:01:07
Problema Floyd-Warshall/Roy-Floyd Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 1.52 kb
#include <stdio.h>
#include <stdlib.h>

#define MAXN 101
// INFINITE * 2 should be < MAXINT
// INFINITE should be > max value(1000) * 100 * 100
#define INFINITE 1000000000
#define min( a, b) ( (a) > (b) ? (b) : (a))

int main() {
    freopen("royfloyd.in", "r", stdin);
    freopen("royfloyd.out", "w", stdout);

    int n;
    int edgeCost[MAXN][MAXN];
    // shortestPath[i][j][k % 2] is the shortest path from i to j using only nodes 1 through k as intermediary points
    int shortestPath[MAXN][MAXN][2];
    int i, j, k, swap1, swap2;

    scanf("%d", &n);
    for (i = 1; i <= n; i ++) {
        for (j = 1; j <= n; j ++) {
            scanf("%d", &edgeCost[i][j]);
            if (edgeCost[i][j] == 0) {
                edgeCost[i][j] = INFINITE;
            }
            shortestPath[i][j][0] = edgeCost[i][j];
        }
    }

    for (k = 1; k <= n; k ++) {
        for (i = 1; i <= n; i ++) {
            for (j = 1; j <= n; j ++) {
                if (i != j) {
                    swap1 = k % 2;
                    swap2 = (k + 1) % 2;
                    shortestPath[i][j][swap1] = min(shortestPath[i][j][swap2], shortestPath[i][k][swap2] + shortestPath[k][j][swap2]);
                }
            }
        }
    }

    for (i = 1; i <= n; i ++) {
        for (j = 1; j <= n; j ++) {
            if (shortestPath[i][j][n % 2] < INFINITE) {
                printf("%d ", shortestPath[i][j][n % 2]);
            } else {
                printf("0 ");
            }
        }
        printf("\n");
    }

    fclose(stdout);
    return 0;
}