Cod sursa(job #807998)

Utilizator romircea2010FMI Trifan Mircea Mihai romircea2010 Data 6 noiembrie 2012 01:04:51
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include <fstream>
#include <vector>
#define INF 2000000000

using namespace std;

int n, m;
int d[50010];
struct muchie
{
    int x, y, cost;
};
vector <muchie> a;

inline void Read()
{
    ifstream f("bellmanford.in");
    f>>n>>m;
    int i;
    muchie aux;
    for(i=1; i<=m; i++)
    {
        f>>aux.x>>aux.y>>aux.cost;
        a.push_back(aux);
    }
    f.close();
}

inline bool BellmanFord()
{
    vector <muchie>::iterator it, final;
    muchie aux;

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

    for(int i=1; i<n; i++)
    {
        it = a.begin();
        final = a.end();
        for(; it!=final; it++)
        {
            aux = *it;
            if(d[aux.y] > d[aux.x] + aux.cost)
            {
                d[aux.y] = d[aux.x] + aux.cost;
            }
        }
    }
    for(it = a.begin(), final = a.end(); it!=final; it++)
    {
        aux = *it;
        if(d[aux.y] > d[aux.x] + aux.cost)
            return true;
    }
    return false;
}

inline void Write(bool ciclu)
{
    ofstream g("bellmanford.out");
    if(ciclu)
        g<<"Ciclu negativ!\n";
    else
    {
        for(int i=2; i<=n; i++)
            g<<d[i]<<" ";
        g<<"\n";
    }
    g.close();
}


int main()
{
    Read();
    bool ciclu;
    ciclu = BellmanFord();
    Write(ciclu);
    return 0;
}