Cod sursa(job #1413784)

Utilizator pulseOvidiu Giorgi pulse Data 2 aprilie 2015 08:44:18
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int maxn = 50010;
const int inf = 2e9;

int n, m, d[maxn], nr[maxn];
vector <pair <int, int> > g[maxn];
queue <int> q;

bool bellman()
{
    for (int i = 2; i <= n; i++)
        d[i] = inf;
    q.push(1);
    while (!q.empty())
    {
        int node = q.front();
        q.pop();
        if (nr[node] >= n) return 0;
        for (vector <pair <int, int> > :: iterator it = g[node].begin(); it != g[node].end(); ++it)
        {
            int v = it -> first;
            int c = it -> second;
            if (d[v] > d[node] + c)
            {
                d[v] = d[node] + c;
                nr[v]++;
                q.push(v);
            }
        }
    }
    return 1;
}

int main()
{
    fin >> n >> m;
    for (int a, b, c; m; --m)
    {
        fin >> a >> b >> c;
        g[a].push_back(make_pair(b, c));
    }
    bool ok = bellman();
    if (!ok) fout << "Ciclu negativ!";
    else
    {
        for (int i = 2; i <= n; i++)
            fout << d[i] << " ";
    }
    return 0;
}