Cod sursa(job #2576450)

Utilizator petrisorvmyVamanu Petru Gabriel petrisorvmy Data 6 martie 2020 19:32:23
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.75 kb
#include <bits/stdc++.h>
#define FILE_NAME "bellmanford"
#define fast ios_base :: sync_with_stdio(0); cin.tie(0);
#pragma GCC optimize("O3")
#define NMAX  50000 + 100
using namespace std;

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

typedef long long ll;
typedef long double ld;
typedef pair<int,int> pi;
typedef pair<ll,ll> llp;
typedef pair<ld,ld> pct;

const int inf = 1 << 30;
const ll mod = 1e9 + 7;
const ld eps = 1e-9;


void add(ll &a , ll b)
{
    a += b;
    a %= mod;
}

void sub(ll &a, ll b)
{
    a = (a - b + mod) % mod;
}

int n, m, viz[NMAX], dist[NMAX];
vector <pi> G[NMAX];
bitset <NMAX> inQ;
queue <int> Q;
int Bellman(int start)
{
    for(int i = 1; i <= n; ++i)
        dist[i] = inf;
    dist[start] = 0;
    viz[start] = 1;
    inQ[start] = 1;
    Q.push(start);
    while(!Q.empty())
    {
        int nod = Q.front();
        Q.pop();
        inQ[nod] = 0;
        for(auto it : G[nod])
        {
            int urm = it.first;
            int cost = it.second;
            if(dist[nod] + cost < dist[urm])
            {
                dist[urm] = dist[nod] + cost;
                viz[urm]++;
                if(viz[urm] >= n - 1)
                    return 0;
                if(!inQ[urm])
                {
                    inQ[urm] = 1;
                    Q.push(urm);
                }

            }
        }
    }
    return 1;
}
int main()
{
    f >> n >> m;
    for(int x,y,z, i = 1; i <= m; ++i)
    {
        f >> x >> y >> z;
        G[x].push_back({y,z});
    }
    if(Bellman(1) == 0)
        g << "Ciclu negativ!";
    else
        for(int i = 2; i <= n; ++i)
            g << dist[i] << ' ';
    f.close();
    g.close();
    return 0;
}