Cod sursa(job #2764977)

Utilizator SabailaCalinSabaila Calin SabailaCalin Data 24 iulie 2021 00:46:13
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.68 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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

const int N_MAX = 50001;
const int POSITIVE_INFINITY = 1000000000;
const int NEGATIVE_INFINITY = -1000000000;

int n, m;
vector <int> dist(N_MAX, POSITIVE_INFINITY);
vector <pair <int, int>> V[N_MAX];
bool negativeCycle = false;

void Read()
{
    f >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int x, y, z;
        f >> x >> y >> z;
        V[x].push_back(make_pair(y, z));
    }
}

void BellmanFord(int startNode)
{
    dist[startNode] = 0;

    for (int k = 1; k <= n; k++)
    {
        for (int i = 1; i <= n; i++)
        {
            for (int j = 0; j < V[i].size(); j++)
            {
                int neighbour = V[i][j].first;
                int cost = V[i][j].second;
                if (dist[i] + cost < dist[neighbour])
                {
                    dist[neighbour] = dist[i] + cost;
                }
            }
        }
    }

    for (int i = 1; i <= n; i++)
    {
        for (int j = 0; j < V[i].size(); j++)
        {
            int neighbour = V[i][j].first;
            int cost = V[i][j].second;
            if (dist[i] + cost < dist[neighbour])
            {
                dist[neighbour] = NEGATIVE_INFINITY;
                negativeCycle = true;
                return;
            }
        }
    }
}

int main()
{
    Read();
    BellmanFord(1);
    if (negativeCycle == true)
    {
        g << "Ciclu negativ!";
    }
    else
    {
        for (int i = 2; i <= n; i++)
        {
            g << dist[i] << " ";
        }
    }
}