Cod sursa(job #1126685)

Utilizator rares96cheseliRares Cheseli rares96cheseli Data 27 februarie 2014 08:58:47
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.06 kb
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");

int N, M, D[50002], cnt[50002], x;
bool viz[50002];
struct ceva{ int y, c; }aux;
vector < ceva > G[50002];
queue < int > Q;

void bellmanford(int sursa)
{
    for (int i=1; i<=N; ++i)
        D[i]=(1<<30);
    D[sursa]=0; Q.push(sursa); viz[1]=1;

    while (Q.size())
    {
        int nod=Q.front(); Q.pop();
        viz[nod]=0; ++cnt[nod];
        if (cnt[nod]==N)
            { g<<"Ciclu negativ!\n"; return; }

        vector <ceva>::iterator it=G[nod].begin();
        for (; it!=G[nod].end(); ++it)
            if (D[nod]+it->c < D[it->y] )
            {
                D[it->y]=D[nod]+it->c;
                if (!viz[it->y])
                    Q.push(it->y), viz[it->y]=1;
            }
    }
}

int main()
{
    f>>N>>M;
    for (int i=1; i<=M; ++i)
        f>>x>>aux.y>>aux.c, G[x].push_back(aux);
    bellmanford(1);
    for (int i=2; i<=N; ++i)
        g<<D[i]<<' ';
    return 0;
}