Cod sursa(job #1489082)

Utilizator AdrianaMAdriana Moisil AdrianaM Data 20 septembrie 2015 15:58:16
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <fstream>
#include <vector>
#include <queue>
#define INF 0x3f3f3f3f
using namespace std;

ifstream is("bellmanford.in");
ofstream os("bellmanford.out");

int n, m;
vector<int> d, cnt;
vector<vector<pair<int, int>>> g;

void Solve();

int main()
{
    Solve();
    is.close();
    os.close();
    return 0;
}

void Solve()
{
    is >> n >> m;
    int a, b, c;
    g = vector<vector<pair<int, int>>>(n + 1);
    while ( m-- )
    {
        is >> a >> b >> c;
        g[a].push_back(make_pair(c, b));
    }
    d = vector<int>(n + 1, INF);
    d[1] = 0;
    queue<int> q;
    q.push(1);
    int nod;
    cnt = vector<int>(n + 1);
    while ( !q.empty() )
    {
        nod = q.front();
        q.pop();
        if ( ++cnt[nod] == n )
        {
            os << "Ciclu negativ!";
            return;
        }
        for ( const auto& nodv : g[nod] )
            if ( d[nodv.second] > d[nod] + nodv.first )
            {
                d[nodv.second] = d[nod] + nodv.first;
                q.push(nodv.second);
            }
    }
    for ( int i = 2; i <= n; ++i )
        if ( d[i] == INF )
            os << "0 ";
        else
            os << d[i] << " ";
}