Cod sursa(job #2601819)

Utilizator paul3ioanCirstean Paul Ioan paul3ioan Data 15 aprilie 2020 11:45:32
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.01 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream cin("bellmanford.in");
ofstream cout("bellmanford.out");
int n ,m , x ,y ,z;
int cost[50001], viz[50001], fr[50001];
queue <int> q;
vector <pair<int,int> > L[50001];
int main() {
    cin >> n >> m;
    for(int i =1 ;i <=n ;i ++)
    {
        cin >> x >> y >> z;
        L[x].push_back({y,z});
    }
    for(int i =1 ;i <=n ;i ++)
        cost[i] = 1e9;
    cost[1] = 0;
    q.push(1);
    fr[1] = 1;
    while(!q.empty())
    {
        int aux = q.front();
        q.pop();
        for(auto i : L[aux])
        {
            if(cost[i.first] > cost[aux] + i.second)
            {
                cost[i.first] = cost[aux] + i.second;
                q.push(i.first);
                fr[i.first]++;
                if(fr[i.first] == n)
                {
                    cout << "Ciclu negativ!";
                    return 0;
                }
            }
        }
    }
    for(int i =2 ;i <=n; i ++)
        cout << cost[i]<<" ";
    return 0;
}