Cod sursa(job #3239849)

Utilizator ChopinFLazar Alexandru ChopinF Data 8 august 2024 00:03:32
Problema Floyd-Warshall/Roy-Floyd Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.08 kb
#include <bits/stdc++.h>
using namespace std;

std::string file = "royfloyd";
std::ifstream fin(file + ".in");
std::ofstream fout(file + ".out");

int main() {
  ios_base::sync_with_stdio(false);
  fin.tie(0);
  fout.tie(0);

  int N;
  fin >> N;

  vector<vector<int>> dist(N, vector<int>(N));

  // Read the input matrix and initialize the distance matrix
  for (int i = 0; i < N; ++i) {
    for (int j = 0; j < N; ++j) {
      fin >> dist[i][j];
      if (dist[i][j] == 0 && i != j) {
        dist[i][j] = INT_MAX; // No direct edge
      }
    }
  }

  // Floyd-Warshall algorithm
  for (int k = 0; k < N; ++k) {
    for (int i = 0; i < N; ++i) {
      for (int j = 0; j < N; ++j) {
        if (dist[i][k] != INT_MAX && dist[k][j] != INT_MAX) {
          dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
        }
      }
    }
  }

  // Output the distance matrix
  for (int i = 0; i < N; ++i) {
    for (int j = 0; j < N; ++j) {
      if (dist[i][j] == INT_MAX) {
        fout << 0 << " ";
      } else {
        fout << dist[i][j] << " ";
      }
    }
    fout << "\n";
  }

  return 0;
}