Cod sursa(job #3211429)

Utilizator Raul_AArdelean Raul Raul_A Data 9 martie 2024 12:09:59
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <bits/stdc++.h>
#define eb emplace_back
#define pii pair<int, int>
#define tpl tuple<int, int, int>
#define oo INT_MAX >> 1
using namespace std;

const string fn("bellmanford");

ifstream in(fn + ".in");
ofstream out(fn + ".out");

#define cin in
#define cout out

const int MAX = 1e5;

vector<pii> g[MAX + 5];
queue<int> q;
bitset<MAX + 5> inq;
vector<int> dist(MAX + 5, oo);
int n, m, apc[MAX + 5];
bool ok = 1;

int main()
{
    cin >> n >> m;
    for (int i = 1, x, y, w; i <= m; i++)
    {
        cin >> x >> y >> w;
        g[x].eb(y, w);
    }
    q.emplace(1);
    inq[1] = 1;
    apc[1]++;
    dist[1] = 0;
    while (!q.empty() and ok)
    {
        int node = q.front();
        q.pop();
        inq[node] = 0;
        for (auto x : g[node])
            if (dist[x.first] > dist[node] + x.second)
            {
                dist[x.first] = dist[node] + x.second;
                if (!inq[x.first])
                {
                    if (apc[x.first] == n)
                    {
                        ok = 0;
                    }
                    else
                        inq[x.first] = 1, q.emplace(x.first), apc[x.first]++;
                }
            }
    }

    if (!ok)
        cout << "Ciclu negativ!";
    else
        for (int i = 2; i <= n; i++)
            cout << dist[i] << ' ';
    return 0;
}