Cod sursa(job #2417978)

Utilizator ALEx6430Alecs Andru ALEx6430 Data 2 mai 2019 17:26:53
Problema Algoritmul Bellman-Ford Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.01 kb
#include <fstream>
#include <vector>
#define INF 100000000
using namespace std;

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

int main()
{
    int n, m;
    in >> n >> m;

    vector<pair<int,int>> v[n+1];

    for(int i = 0; i < m; i++)
    {
        int x, y, c;
        in >> x >> y >> c;

        v[x].push_back({y,c});
    }

    vector<int> d(n+1,INF);
    d[1] = 0;

    for(int i = 1; i < n; i++)
        for(int j = 0; j < v[i].size(); j++)
        {
            int nod = v[i][j].first;
            int cost = v[i][j].second;

            d[nod] = min(d[nod],d[i]+cost);
        }

    for(int i = 1; i <= n; i++)
        for(int j = 0; j < v[i].size(); j++)
        {
            int nod = v[i][j].first;
            int cost = v[i][j].second;

            if(d[i]+cost < d[nod])
            {
                out << "Ciclu negativ!";
                return 0;
            }
        }

    for(int i = 2; i <= n; i++) out << d[i] << ' ';

    return 0;
}