Cod sursa(job #2614570)

Utilizator raresAlex95Rares Stan raresAlex95 Data 11 mai 2020 22:14:53
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <iostream>
#include <fstream>
#include <vector>

#define INF 2500000
#define N_MAX 50001
#define M_MAX 250001

using namespace std;

ifstream in("bellmanford.in");
ofstream out("bellmanford.out");

struct edge
{
  int src, dst, cost;
} edges[M_MAX];
int n, m, distances[N_MAX];

void input()
{
  int a, b, c;

  in >> n >> m;

  for (int i = 0; i < m; i++)
  {
    in >> a >> b >> c;
    edges[i] = {a - 1, b - 1, c};
  }
}

void output()
{
  for (auto e : edges)
  {
    if (distances[e.dst] > distances[e.src] + e.cost)
    {
      out << "Ciclu negativ!";
      return;
    }
  }

  for (int i = 1; i < n; i++)
  {
    out << distances[i] << ' ';
  }
}

void setup()
{
  for (int i = 0; i < n; i++)
  {
    distances[i] = INF;
  }

  distances[0] = 0;
}

void bellmanFord()
{
  for (int i = 0; i < n - 1; i++)
  {
    for (auto e : edges)
    {
      if (distances[e.dst] > distances[e.src] + e.cost)
      {
        distances[e.dst] = distances[e.src] + e.cost;
      }
    }
  }
}

int main()
{

  input();
  setup();
  bellmanFord();
  output();

  return 0;
}