Cod sursa(job #3213879)

Utilizator leelcheeseCiovnicu Denis leelcheese Data 13 martie 2024 16:12:51
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <bits/stdc++.h>
#include <unordered_map>
#define nmax 50006
#define MOD 1999999973
#define INF 2012345678
#define ll long long
using namespace std;
//#define fin cin
//#define fout cout

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

int n, m;
vector <pair <int, int>> L[nmax];
queue <int> q;
int cnt[nmax], d[nmax];
bitset <nmax> viz;

bool BellmanFord(int k)
{
    int i, x, cost;
    for (i = 1; i <= n; i++)
        d[i] = INF;
    d[k] = 0;
    q.push(k);
    cnt[k]++;
    while (!q.empty())
    {
        k = q.front();
        q.pop();
        viz[k] = 0;
        for (auto w : L[k])
        {
            x = w.second;
            cost = w.first;
            if (d[x] > d[k] + cost)
            {
                d[x] = d[k] + cost;
                if (viz[x] == 0)
                {
                    viz[x] = 1;
                    q.push(x);
                    cnt[x]++;
                    if (cnt[x] > n)
                        return 1;
                }
            }
        }
    }
    return 0;
}

int main()
{
    int i, x, y, c;
    fin >> n >> m;
    for (i = 1; i <= m; i++)
    {
        fin >> x >> y >> c;
        L[x].push_back({ c, y });
    }

    if (BellmanFord(1))
        fout << "Ciclu negativ!";
    else
        for (i = 2; i <= n; i++)
            fout << d[i] << " ";
    fout << "\n";

    fin.close();
    fout.close();
    return 0;
}