Cod sursa(job #2121680)

Utilizator hantoniusStan Antoniu hantonius Data 4 februarie 2018 08:46:02
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.7 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
#include <climits>
#define MAXN 50001
using namespace std;

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

vector <pair <int, int> > v[MAXN];
queue <int> coada;
bitset <MAXN> in_queue(false);

int dist[MAXN], count_in_queue[MAXN], n, m, negativ;

void read()
{
    int x, y, c;

    fin >> n >> m;
    for (int i = 0; i < m; ++i) {
        fin >> x >> y >> c;
        v[x].push_back(make_pair(y, c));
    }
}

void init()
{
    for (int i = 1; i <= n; ++i)
        dist[i] = INT_MAX;
}

void solve()
{
    int aux;
    vector <pair <int, int> >::iterator it;

    coada.push(1);
    dist[1] = 0;
    in_queue[1] = true;
    while (coada.empty() == false) {
        aux = coada.front();
        coada.pop();
        in_queue[aux] = false;
        for (it = v[aux].begin(); it != v[aux].end(); ++it) {
            if (dist[it->first] > dist[aux] + it->second) {
                dist[it->first] = dist[aux] + it->second;
                if (in_queue[it->first] == false) {
                    if (count_in_queue[it->first] > n) {
                        negativ = 1;
                        return;
                    }
                    count_in_queue[it->first]++;
                    coada.push(it->first);
                    in_queue[it->first] = true;
                }
            }
        }
    }
}

void write()
{
    if (negativ == 1)
        fout << "Ciclu negativ!";
    else
        for (int i = 2; i <= n; ++i)
            fout << dist[i] << ' ';
}

int main()
{
    read();
    init();
    solve();
    write();
    return 0;
}