Cod sursa(job #2456666)

Utilizator igsifvevc avb igsi Data 15 septembrie 2019 01:22:00
Problema Floyd-Warshall/Roy-Floyd Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <algorithm>
#include <fstream>
#include <vector>

std::vector<std::vector<int>> solve(std::vector<std::vector<int>> &G) {
  int n = G.size();

  for (int k = 0; k < n; k++) {
    for (int u = 0; u < n; u++) {
      for (int v = 0; v < n; v++) {
        if (u != v && G[u][k] != 0 && G[k][v] != 0) {
          if (G[u][v] == 0) {
            G[u][v] = G[u][k] + G[k][v];
          } else {
            G[u][v] = std::min(G[u][v], G[u][k] + G[k][v]);
          }
        }
      }
    }
  }

  return G;
}

std::vector<std::vector<int>> read();
void write(const std::vector<std::vector<int>> &);

int main() {
  auto G = read();
  auto D = solve(G);
  write(D);

  return 0;
}

std::vector<std::vector<int>> read() {
  std::ifstream fin("royfloyd.in");
  int n;

  fin >> n;

  std::vector<std::vector<int>> G(n, std::vector<int>(n, 9));
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      fin >> G[i][j];
    }
  }

  return G;
}

void write(const std::vector<std::vector<int>> &D) {
  std::ofstream fout("royfloyd.out");

  for (auto &row : D) {
    for (auto d : row) {
      fout << d << ' ';
    }
    fout << '\n';
  }
}