Cod sursa(job #1380197)

Utilizator viuscenkoViktor Iuscenko viuscenko Data 6 martie 2015 23:14:39
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.88 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
FILE *in = fopen("bellmanford.in", "r");
FILE *out = fopen("bellmanford.out", "w");
#endif

int n, m;
int cnt[MAXN];
vector<pair<int, int> > vec[MAXN];

int main() {
    int x, y, c;

    fscanf(in, "%d%d", &n, &m);
    for(int i = 0; i < m; ++i) {
        fscanf(in, "%d%d%d", &x, &y, &c);
        vec[x].pub(mp(y, c));
    }

    vector<int> dist(n + 1, inf);
    bitset<MAXN> viz(false);
    queue<int> Q;
    bool negativeCycle = false;

    Q.push(1); dist[1] = 0; viz[1].flip();
    while(!Q.empty() && !negativeCycle) {
        x = Q.front(); Q.pop();
        viz[x] = false;
        for(auto it: vec[x]) if(dist[x] < inf) {
            if(dist[it.fs] > dist[x] + it.sc) {
                dist[it.fs] = dist[x] + it.sc;
                if(!viz[it.fs]) {
                    if(cnt[it.fs] <= n) {
                        viz[it.fs] = 1;
                        Q.push(it.fs);
                    } else {
                        negativeCycle = true;
                        break;
                    }
                }
            }
        }
    }

    if(negativeCycle)
        fprintf(out, "Ciclu negativ!\n");
    else
        for(int i = 2; i <= n; ++i)
            fprintf(out, "%d ", dist[i]);
    return 0;
}