Cod sursa(job #1337882)

Utilizator Corina1997Todoran Ana-Corina Corina1997 Data 9 februarie 2015 16:46:51
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

#define INF 0x3f3f3f3f

vector<vector<pair<int, int> > > G;
vector<int> d, nr;
vector<bool> s;
int n, m, x, y, cost, ciclu;

queue<int> Q;

void Solve();

int main()
{
    is >> n >> m;
    G.resize(n+1);
    d.resize(n+1, INF);
    s.resize(n+1, false);
    nr.resize(n+1, 0);

    for ( int i = 1; i <= m; i++ )
    {
        is >> x >> y >> cost;
        G[x].push_back(make_pair(y, cost));
    }
    Solve();
    if ( ciclu == 1 )
        os << "Ciclu negativ!";
    else
    {
        for ( vector<int>::iterator it = d.begin() + 2; it != d.end(); it++ )
            os << *it << ' ';
    }
    is.close();
    os.close();
    return 0;
}


void Solve()
{
    Q.push(1);
    d[1] = 0;
    s[1] = true;
    int aux;
    while( !Q.empty() )
    {
        aux = Q.front();
        s[aux] = false;
        Q.pop();
        for ( const auto& f : G[aux] )
        {
            if( d[f.first] > d[aux] + f.second )
            {
                d[f.first] = d[aux] + f.second;
                if ( !s[f.first] )
                {
                    nr[f.first]++;
                    if ( nr[f.first] == n )
                    {
                        ciclu = 1;
                        return;
                    }
                    Q.push(f.first);
                    s[f.first] = true;
                }
            }
        }
    }
}