Cod sursa(job #1824004)

Utilizator tudormaximTudor Maxim tudormaxim Data 7 decembrie 2016 10:08:21
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.77 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
using namespace std;

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

const int nmax = 5e4 + 5;
const int oo = 1 << 29;
vector <pair<int,int> > G[nmax];
int Dist[nmax], Cnt[nmax];

bool Bellman_Ford(int source, int n) {
    queue <int> Q;
    bitset <nmax> Vis = 0;
    vector < pair <int,int> > :: iterator it;
    int node, i;
    for (i = 1; i <= n; i++) {
        Dist[i] = oo;
    }
    Dist[source] = 0;
    Cnt[source] = 1;
    Q.push(source);
    while (!Q.empty()) {
        node = Q.front();
        Vis[node] = false;
        Q.pop();
        for (it = G[node].begin(); it != G[node].end(); it++) {
            if (Dist[it->first] > Dist[node] + it->second) {
                Dist[it->first] = Dist[node] + it->second;
                if (Vis[it->first] == false) {
                    Vis[it->first] = true;
                    Q.push(it->first);
                    Cnt[it->first]++;
                    if (Cnt[it->first] > n) {
                        return true;
                    }
                }
            }
        }
    }
    return false;
}

int main() {
    ios_base :: sync_with_stdio (false);
    int n, m, x, y, c, i;
    fin >> n >> m;
    for (i = 1; i <= m; i++) {
        fin >> x >> y >> c;
        G[x].push_back(make_pair(y, c));
    }
    bool Cycle = Bellman_Ford(1, n);
    if (Cycle == true) {
        fout << "Ciclu negativ!";
    } else {
        for (i = 2; i <= n; i++) {
            if (Dist[i] == oo) {
                fout << "0 ";
            } else {
                fout << Dist[i] << " ";
            }
        }
    }
    fin.close();
    fout.close();
    return 0;
}