Cod sursa(job #1337964)

Utilizator tatianazTatiana Zapirtan tatianaz Data 9 februarie 2015 17:53:45
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 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 > > > v;
queue <int> Q;

bool oke[50001], cic_neg;
int nd[50001], cnt[50001], d[50001];
int n, m;
int x, y, z;
int nod, cost;

int main()
{
    is >> n >> m;
    v.resize(n+1);
    for ( int i = 1; i <= m; ++i )
    {
        is >> x >> y >> z;
        v[x].push_back(make_pair(y, z));
    }

    for ( int i = 2; i <= n; ++i )
        d[i] = INF;

    Q.push(1);
    while ( !Q.empty() && !cic_neg )
    {
        x = Q.front();
        Q.pop();
        oke[x] = false;
        for ( int i = 0; i < v[x].size(); ++i )
        {
            nod = v[x][i].first;
            cost = v[x][i].second;
            if ( d[nod] > d[x] + cost )
            {
                d[nod] = d[x] + cost;
                if ( !oke[nod] )
                {
                    if ( cnt[nod] > n )
                        cic_neg = true;
                    else
                    {
                        cnt[nod]++;
                        Q.push(nod);
                        oke[nod] = true;
                    }
                }
            }

        }
    }

    if ( cic_neg )
        os << "Ciclu negativ!";
    else
        for ( int i = 2; i <= n; ++i )
            os << d[i] << ' ';

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