Cod sursa(job #2569043)

Utilizator BluThund3rRadu George BluThund3r Data 4 martie 2020 10:53:18
Problema Algoritmul Bellman-Ford Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

const int inf = 1e3 + 1;
int n, m;

int main()
{
    in.tie(0);
    ios_base::sync_with_stdio(0);

    in >> n >> m;
    vector < pair <int, int> > adj[n + 1];

    for(int i = 1; i <= m; ++ i)
    {
        int x, y, cost;
        in >> x >> y >> cost;
        adj[x].push_back({y, cost});
    }

    vector <bool> added(n + 1, false);
    vector <int> dist(n + 1, inf), visits (n + 1, 0);
    queue <int> q;

    dist[1] = 0;
    q.push(1);

    while(!q.empty())
    {
        int node = q.front();
        q.pop();
        ++ visits[node];
        added[node] = false;

        if(visits[node] == n)
        {
            out << "Ciclu negativ!";
            return 0;
        }

        for(auto i : adj[node])
        {
            int nextnode = i.first, weight = i.second;

            if(dist[nextnode] > dist[node] + weight)
            {
                dist[nextnode] = dist[node] + weight;

                if(!added[nextnode])
                {
                    q.push(nextnode);
                    added[nextnode] = true;
                }
            }
        }
    }

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

    return 0;
}