Cod sursa(job #605443)

Utilizator vladtarniceruVlad Tarniceru vladtarniceru Data 28 iulie 2011 19:36:26
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
# include <fstream>
# include <vector>
# include <set>
# include <cstdlib>
using namespace std;

vector < pair <int, int> > LIST[50100];
int n, m, x, y, cost, dist[50100], ap[50100], apQ[50100];
set <pair <int, int> > st;
ifstream f ("bellmanford.in");
ofstream g ("bellmanford.out");

void bellmanford ()
{
    for (int i = 1; i <= n; ++i) dist[i] = 2000000000;
    st.insert (make_pair (0, 1)); // cost, nod
    for (; !Q.empty (); )
    {
        int cost = st.front () -> first, nod = st.front () -> second;
        st.erase ((*st.front ()));
        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
                    {
                        st.insert (it);
                        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 ();
}