Cod sursa(job #1648674)

Utilizator BaweeLazar Vlad Bawee Data 11 martie 2016 11:15:20
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <fstream>
#include <vector>
#include <deque>

using namespace std;

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

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

void bellman(int start)
{
    for(int i = 1; i <= n; ++i)
        d[i] = 1 << 20;
    d[start] = 0;
    q.push_back(start);
    while(!q.empty())
    {
        int u = q.front();
        q.pop_front();
        for(auto it = G[u].begin(); it != G[u].end() && !cicle; ++it)
            if(d[it -> first] > d[u] + it -> second)
            {
                d[it -> first] = d[u] + 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));
    }

    int start = 1;
    bellman(start);
    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;
}