Cod sursa(job #2221876)

Utilizator tiberiu392Tiberiu Ungurianu tiberiu392 Data 16 iulie 2018 00:54:40
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <fstream>
#include <vector>
#include <queue>
#define DIM 50005
#define inf 1000000005
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
vector < int > ls[DIM], lc[DIM];
int n, m, x, y, cost, i;
queue < int > Q;
int seen[DIM], cnt[DIM];

int main()
{
    f >> n >> m;
    while ( m -- )
    {
        f >> x >> y >> cost;
        ls[x].push_back(y);
        lc[x].push_back(cost);
    }
     for ( int i = 2 ; i <= n ; i ++ )
        seen[i] = inf;
    Q.push(1);

    while (Q.empty()==0)
     {
        int old_n = Q.front();
        Q.pop();
        int l = ls[old_n].size();
        for ( int i = 0 ; i < l ; i ++ )
         {
            int new_n = ls[old_n][i];
            int new_c = lc[old_n][i];
            if (seen[old_n]+new_c < seen[new_n])
            {
                seen[new_n] = seen[old_n]+new_c;
                cnt[new_n]++;
                Q.push(new_n);
            }
            if (cnt[new_n] >= n)
             {
                g << "Ciclu negativ!";
                return 0;
            }
        }
    }
    for ( int i = 2 ; i <= n ; i ++ )
        g << seen[i] << ' ';
    return 0;
    return 0;
}