Cod sursa(job #605439)

Utilizator vladtarniceruVlad Tarniceru vladtarniceru Data 28 iulie 2011 18:47:20
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 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];

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;
    for (; !Q.empty (); )
    {
        int nod = Q.front ();
        Q.pop ();
        for (vector <pair <int, int> > :: iterator it = LIST[nod].begin (); it != LIST[nod].end (); ++it)
        {
            if (dist[it -> first] > dist[nod] + it -> second)
            {
                if (ap[it -> first] > n)
                {
                    g << "Ciclu negativ!";
                    exit (0);
                }
                else
                {
                    dist[it -> first] = dist[nod] + it -> second;
                    Q.push (it -> first);
                    ap[ap[it -> first]] = ap[nod] + 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 ();
}