Cod sursa(job #3130205)

Utilizator NiffSniffCojocaru Calin Marcu NiffSniff Data 17 mai 2023 01:10:12
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
string file = "bellmanford";
ifstream cin (file + ".in");
ofstream cout (file + ".out");
const int N = 50000;
struct muchie{
    int nod, cost;
};
vector <muchie> L[N+1];
int d[N+1], prin_nod[N+1],n;
bool bfs()
{
    queue <int> Q;
    Q.push(1);
    bool ok = 0;
    d[1] = 0;
    while (!Q.empty())
    {
        int x = Q.front();
        Q.pop();
        for (auto y : L[x])
        {
            if (d[y.nod] > d[x] + y.cost)
            {
                d[y.nod] = d[x] + y.cost;
                prin_nod[y.nod]++;
                Q.push(y.nod);
            }
            if (prin_nod[y.nod] == n)
            {
                return 1;
            }
        }
    }
    return 0;
}
int main ()
{
    int m,x,y,z;
    cin >> n >> m;
    for (int i=1; i<=n; i++)
        d[i] = 50000000;
    for (int i=1; i<=m; i++)
    {
        cin >> x >> y >> z;
        L[x].push_back({y,z});
    }
    if (bfs())
    {
        cout << "Ciclu negativ!";
    }
    else
    {
        for (int i=2; i<=n; i++)
            cout << d[i] << ' ';
    }
}