Cod sursa(job #1921925)

Utilizator razvan99hHorhat Razvan razvan99h Data 10 martie 2017 15:22:45
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.12 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define DM 50005
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");

int n, m, a, b, c, viz[DM], dist[DM];
const int INF = (1 << 30);
vector <pair<int, int> > g[DM];
queue <int> q;

void bellman_ford()
{
    for(int i = 2; i <= n; i++)
        dist[i] = INF;
    q.push(1);
    while(!q.empty())
    {
        int nod = q.front();
        q.pop();
        for(auto it : g[nod])
            if(dist[it.first] > dist[nod] + it.second)
            {
                dist[it.first] = dist[nod] + it.second;
                q.push(it.first);
                viz[it.first]++;
                if(viz[it.first] > n)
                {
                    fout << "Ciclu negativ!";
                    return;
                }
            }
    }
    for(int i = 2; i <= n; i++)
        fout << dist[i] << ' ';
}

int main()
{
    fin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        fin >> a >> b >> c;
        g[a].push_back(make_pair(b,c));
    }
    bellman_ford();
    return 0;
}