Cod sursa(job #2407464)

Utilizator Cezar211Popoveniuc Cezar Cezar211 Data 16 aprilie 2019 21:29:21
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include <bits/stdc++.h>
#define NM 50005
using namespace std;
ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");
void read();
int n, m, viz[NM], dist[NM];
vector<pair<int,int>> v[NM];
queue<int> q;
int main()
{
    read();
    for(int i=2; i<=n; i++)
        dist[i] = INT_MAX/2-1;
    q.push(1);
    viz[1] = 1;
    while(!q.empty())
    {
        int nod = q.front();
        q.pop();
        for(auto it : v[nod])
            if(viz[it.first] == n-1)
            {
                fout << "Ciclu negativ!";
                return 0;
            }
            else if(dist[it.first] > dist[nod]+it.second)
            {
                dist[it.first] = dist[nod] + it.second;
                viz[it.first]++;
                q.push(it.first);
            }
    }
    for(int i=2; i<=n; i++)
        fout << dist[i] << ' ';
    return 0;
}
void read()
{
    fin >> n >> m;
    for(int i=1; i<=m; i++)
    {
        int x, y, c;
        fin >> x >> y >> c;
        v[x].push_back({y, c});
    }
}