Cod sursa(job #1398257)

Utilizator irimiecIrimie Catalin irimiec Data 24 martie 2015 08:30:49
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
#include <bits/stdc++.h>

using namespace std;

#define     mp              make_pair
#define     fs              first
#define     sc              second
#define     pob             pop_back
#define     pub             push_back
#define     eps             1E-7
#define     sz(a)           a.size()
#define     count_one       __builtin_popcount;
#define     count_onell     __builtin_popcountll;
#define     fastIO          ios_base::sync_with_stdio(false)
#define     PI              (acos(-1.0))
#define     linf            (1LL<<62)//>4e18
#define     inf             (0x7f7f7f7f)//>2e9

#define MAXN 50010

#ifndef ONLINE_JUDGE
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
#endif

int n, m;
vector<pair<int, int> > vec[MAXN];
bitset<MAXN> viz;
queue<int> Q;
int dist[MAXN], cnt[MAXN];
bool negativeCycle;

void bford() {
    for(int i = 2; i <= n; ++i)
        dist[i] = inf;

    int nod;
    for(Q.push(1), viz[1] = true, negativeCycle = false; !Q.empty() && !negativeCycle; Q.pop()) {
        nod = Q.front();

        if(dist[nod] != inf)
        for(auto it: vec[nod]) {
            if(dist[it.fs] > dist[nod] + it.sc) {
                dist[it.fs] = dist[nod] + it.sc;
                if(!viz[it.fs])
                    if(cnt[it.fs] > n)
                        negativeCycle = true;
                    else
                        viz[it.fs] = true, Q.push(it.fs), ++cnt[it.fs];
            }
        }
        viz[nod] = false;
    }
}

int main() {
    f >> n >> m;

    int a, b, c;
    for(int i = 0; i < m; ++i)
        f >> a >> b >> c, vec[a].pub(mp(b, c));

    bford();

    if(negativeCycle)
        g << "Ciclu negativ!\n";
    else
        for(int i = 2; i <= n; ++i)
            g << dist[i] << " ";

    return 0;
}