Cod sursa(job #2767906)

Utilizator Edyci123Bicu Codrut Eduard Edyci123 Data 8 august 2021 14:35:39
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
#define NMAX 50005

using namespace std;

ifstream f("bellmanford.in");
ofstream g("bellmanford.out");

int n, m, nriq[NMAX], dist[NMAX];
vector <pair <int, int>> edges[NMAX];
bitset <NMAX> iq;
queue <int> q;

bool bf()
{
    bool negCycle = 0;
    for(int i = 1; i <= n; i++)
        dist[i] = INF;
    q.push(1);
    iq[1] = 1;
    nriq[1] = 1;
    dist[1] = 0;

    while(!q.empty())
    {
        int nod = q.front();
        q.pop();
        iq[nod] = 0;
        for(auto k : edges[nod])
            if(dist[k.first] > dist[nod] + k.second)
            {
                dist[k.first] = dist[nod] + k.second;
                if(!iq[k.first])
                {
                    iq[k.first] = 1;
                    q.push(k.first);
                    nriq[k.first]++;
                    if(nriq[k.first] == n)
                        return 0;
                }
            }
    }
    return 1;
}

int main()
{
    f >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        int x, y, cost;
        f >> x >> y >> cost;
        edges[x].push_back(make_pair(y, cost));

    }

    if(!bf())
    {
        g << "Ciclu negativ!";
        return 0;
    }

    for(int i = 2; i <= n; i++)
        g << dist[i] << " ";



    return 0;
}