Cod sursa(job #2858107)

Utilizator stalecuAlecu Stefan-Iulian stalecu Data 26 februarie 2022 23:52:30
Problema Floyd-Warshall/Roy-Floyd Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.7 kb
#include <vector>
#include <fstream>
#include <iostream>

#include <stdexcept>
#define INF 0x3f3f3f3f
std::vector<std::vector<int>>
floydwarshall(const std::vector<std::vector<int>> &graph) {
  if (graph.size() != graph[0].size()) {
    throw std::invalid_argument("Matricea trebuie să fie pătratică");
  }

  int size = graph.size();
  std::vector<std::vector<int>> dist(size, std::vector<int>(size, INF));
  for (int i = 0; i < size; i++) {
    for (int j = 0; j < size; j++) {
      dist[i][i] = 0;
      dist[i][j] = graph[i][j];
    }
  }

  for (int k = 0; k < size; k++)
    {
      for (int i = 0; i < size; i++)
        {
          for (int j = 0; j < size; j++)
            {
              dist[i][j] = std::min(dist[i][j], dist[i][k] + dist[k][j]);

            }
        }
    }

  for (int i = 0; i < size; i++) {
    for (int j = 0; j < size; j++) {
      if (dist[i][j] == INF) {
        dist[i][j] = 0;
      }
    }
  }
  return dist;
}

int main() {
  std::fstream in;
  in.open("royfloyd.in", std::ios::in);

  long long M;
  if (!in.is_open()) {
    std::cerr << "File could not be opened." << std::endl;
    exit(EXIT_FAILURE);
  }

  in >> M;
  std::fstream out;
  out.open("royfloyd.out", std::ios::out);
  if (!out.is_open()) {
    std::cerr << "File could not be written to." << std::endl;
    exit(EXIT_FAILURE);
  }
  std::vector<std::vector<int>> graph(M, std::vector<int>(M));
  long long el;
  for (int i = 0; i < M; i++) {
    for (int j = 0; j < M; j++) {
      in >> graph[i][j];
    }
  }
  auto dist = floydwarshall(graph);
  for (int i = 0; i < M; i++) {
    for (int j = 0; j < M; j++) {
      out<< graph[i][j] << " ";
    }
        out << "\n";
  }
  in.close();
  out.close();
  exit(EXIT_SUCCESS);
}