Cod sursa(job #1379037)

Utilizator Mr.DoomRaul Ignatus Mr.Doom Data 6 martie 2015 15:51:34
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.54 kb
#include <fstream>
#include <queue>
#include <vector>
#include <bitset>
using namespace std;

#define INF 0x3f3f3f3f

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

vector<vector<pair<int, int> > > G;
vector<int> D, Count;
int n, m;
queue<int> Q;
bitset<50001> v;

bool BellmanFord();
void Read();

int main()
{
    Read();
    if ( BellmanFord() )
        for ( int i = 2; i <= n; ++i )
            os << D[i] << ' ';
    else
        os << "Ciclu negativ!";

    is.close();
    os.close();
    return 0;
}

bool BellmanFord()
{
    int node;
    Q.push(1);
    D[1] = 0;
    Count[1] = 1;
    while ( !Q.empty() )
    {
        node = Q.front();
        Q.pop();
        v[node] = 0;
        for ( const auto& g : G[node] )
        {
            if ( D[g.first] > D[node] + g.second && !v[g.first] )
            {
                if ( Count[g.first] > n )
                    return false;
                D[g.first] = D[node] + g.second;
                Q.push(g.first);
                Count[g.first]++;
                v[g.first] = 1;
            }
            if ( D[g.first] > D[node] + g.second && v[g.first] )
                D[g.first] = D[node] + g.second;
        }
    }
    return true;
}

void Read()
{
    is >> n >> m;
    G = vector<vector<pair<int, int> > >(n + 1);
    D = vector<int>(n + 1, INF);
    Count = vector<int>(n + 1);
    int x, y, cost;
    for ( int i = 1; i <= m; ++i )
    {
        is >> x >> y >> cost;
        G[x].push_back({y, cost});
    }
}