Cod sursa(job #605441)

Utilizator vladtarniceruVlad Tarniceru vladtarniceru Data 28 iulie 2011 18:56:17
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
# include <fstream>
# include <vector>
# include <queue>
# include <cstdlib>
using namespace std;

vector < pair <int, int> > LIST[50100];
int n, m, x, y, cost, dist[50100], ap[50100], apQ[50100];

queue <int> Q;

ifstream f ("bellmanford.in");
ofstream g ("bellmanford.out");

void bellmanford ()
{
    Q.push (1);
    for (int i = 1; i <= n; ++i) dist[i] = 2000000000;
    dist[1] = 0;
    apQ[1] = 1;
    for (; !Q.empty (); )
    {
        int nod = Q.front ();
        Q.pop ();
        apQ[nod] = 0;
        for (vector <pair <int, int> > :: iterator it = LIST[nod].begin (); it != LIST[nod].end (); ++it)
        {
            if (dist[it -> first] > dist[nod] + it -> second)
            {
                dist[it -> first] = dist[nod] + it -> second;
                if (!apQ[it -> first])
                {
                    if (ap[it -> first] > n)
                    {
                        g << "Ciclu negativ!";
                        exit (0);
                    }
                    else
                    {
                        Q.push (it -> first);
                        ap[ap[it -> first]] = ap[nod] + 1;
                        apQ[it -> first] = 1;
                    }
                }
            }
        }
    }
}
int main ()
{
    f >> n >> m;
    for (int i = 1; i <= m; ++i)
    {
        f >> x >> y >> cost;
        LIST[x].push_back (make_pair (y, cost));
    }
    bellmanford ();
    for (int i = 2; i <= n; ++i)
        g << dist[i] << ' ';
    return 0;
    g.close ();
}