Cod sursa(job #2169398)

Utilizator netfreeAndrei Muntean netfree Data 14 martie 2018 15:13:26
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.18 kb
#include <bits/stdc++.h>
#define pii pair<int, int>
#define x first
#define y second

using namespace std;

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

const int N_MAX = 50000 + 5;
const int inf = 0x3f3f3f3f;

queue<int> q;

int viz[N_MAX];
bitset<N_MAX> inq;

vector<pii> vec[N_MAX];
int dp[N_MAX], n, m;

int main()
{
    fin >> n >> m;
    while(m--){
        int a, b, c;
        fin >> a >> b >> c;
        vec[a].push_back({b,c});
    }

    memset(dp, inf, sizeof(dp));

    dp[1] = 0;
    q.push(1);
    while(!q.empty()){
        int nod = q.front();
        q.pop();
        inq[nod] = false;
        viz[nod] ++;

        if(viz[nod] > n + 1){
            fout << "Ciclu negativ!";
            return 0;
        }

        for(auto v : vec[nod])
            if(dp[v.x] > dp[nod] + v.y){
                dp[v.x] = dp[nod] + v.y;
                if(!inq[v.x]){
                    q.push(v.x);
                    inq[v.x] = true;
                }
            }
    }

    for(int i = 2; i<=n; ++i)
        if(dp[i] < inf)
            fout << dp[i] << " ";
        else
            fout << "0 ";
    return 0;
}