Cod sursa(job #1605095)

Utilizator BaweeLazar Vlad Bawee Data 18 februarie 2016 19:25:41
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include <fstream>
#include <vector>
#include <deque>

using namespace std;

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

deque<int> q;
vector< pair<int , int> > G[50001];
int d[50001] , n , m , x , y , c , C[50001];
bool cicle;

void SwaG(int start)
{
    q.push_back(start);
    for(int i = 1; i <= n; ++i) d[i] = 1 << 20;
    d[start] = 0;

    while(!q.empty())
    {
        int nod = q.front();
        q.pop_front();
        for(auto it = G[nod].begin(); it != G[nod].end() && !cicle; ++it)
            if(d[it -> first] > d[nod] + it -> second)
            {
                d[it -> first] = d[nod] + it -> second;
                q.push_back(it -> first);
                if(C[++(it -> first)] > n) cicle = true;
            }
    }
}


int main()
{
    f >> n >> m;
    for(int i = 1; i <= m; ++i)
    {
        f >> x >> y >> c;
        G[x].push_back(make_pair(y,c));
    }

    SwaG(1);
    if(cicle) g << "Ciclu negativ!";
    else
        for(int i = 2; i <= n; ++i)
        {
            if(d[i] == 1 << 20) d[i] = 0;
            g << d[i] << " ";
        }

    return 0;
}