Cod sursa(job #1821468)

Utilizator OFY4Ahmed Hamza Aydin OFY4 Data 3 decembrie 2016 10:49:30
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int inf = 1000000000, Max = 50010;

struct edge
{
    int nod, z;
};

vector<edge> v[Max];
queue<int> q;
int d[Max], sayi[Max], n;
char girmis[Max];

int bellmanFord(int nod)
{
    for(int i = 1; i <= n; ++i)
        d[i] = inf;
    d[nod] = 0;
    q.push(nod);
    girmis[nod] = 1;

    while(!q.empty())
    {
        int nod = q.front();
        q.pop();
        girmis[nod] = 0;

        for(vector<edge> :: iterator it = v[nod].begin(); it != v[nod].end(); ++it)
        {
            if(d[it -> nod] > d[nod] + it -> z)
            {
                d[it -> nod] = d[nod] + it -> z;
                if(!girmis[it -> nod])
                {
                    if(++sayi[it -> nod] == n)
                        return 0;
                    q.push(it -> nod);
                    girmis[it -> nod] = 1;
                }
            }
        }
    }
    return 1;
}

int main()
{
    int m, x, y, z;
    in >> n >> m;
    for(int i = 1; i <= m; ++i)
    {
        in >> x >> y >> z;
        v[x].push_back({y, z});
    }

    if(!bellmanFord(1))
        out << "Ciclu negativ!";
    else
    {
        for(int i = 2; i <= n; ++i)
            out << d[i] << " ";
    }

    return 0;
}