Cod sursa(job #2034724)

Utilizator vasi461Vasiliu Dragos vasi461 Data 8 octombrie 2017 13:02:21
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

#define MAX 50005
#define INF 50000005

int n, m, a, b, c, d[MAX], k[MAX];
bool viz[MAX];
vector<pair<int, int> > g[MAX];
queue<int> q;

bool bellmanford()
{
    for(int i = 1; i <= MAX; ++i)
    {
        d[i] = INF;
        viz[i] = false;
    }
    q.push(1);
    d[1] = 0;
    viz[1] = true;
    k[1] = 1;
    while(!q.empty())
    {
        int x = q.front();
        q.pop();
        viz[x] = false;
        for(int i = 0; i < g[x].size(); ++i)
        {
            if(d[x] + g[x][i].second < d[g[x][i].first])
            {
                d[g[x][i].first] = d[x] + g[x][i].second;
                if(!viz[g[x][i].first])
                {
                    q.push(g[x][i].first);
                    viz[g[x][i].first] = true;
                    k[g[x][i].first]++;
                    if(k[g[x][i].first] > n)
                    {
                        return false;
                    }
                }
            }
        }
    }
    return true;
}

int main()
{
    cin >> n >> m;
    for(int i = 1; i <= m; ++i)
    {
        cin >> a >> b >> c;
        g[a].push_back(make_pair(b, c));
    }
    bool cn = bellmanford();
    if(!cn)
    {
        cout << "Ciclu negativ!" << '\n';
        return 0;
    }
    for(int i = 2; i <= n; ++i)
    {
        cout << d[i] << ' ';
    }
    cout << '\n';
    return 0;
}