Cod sursa(job #1921936)

Utilizator raulrusu99Raul Rusu raulrusu99 Data 10 martie 2017 15:25:51
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.06 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
#define N_MAX 50005
#define inf (1<<31)-1
vector <pair <int, int> > G[N_MAX];
queue <int> Q;
int ap[N_MAX], dist[N_MAX];
int n, m;
int main()
{
    f >> n >> m;
    int x, y, z;
    for(int i = 1; i <= m ; i++)
    {
        f >> x >> y >> z;
        G[x].push_back(make_pair(y, z));
    }
    for(int i = 1; i <= n; i++)
        dist[i] = inf;
    dist[1] = 0;
    Q.push(1);
    int nod;
    while(!Q.empty())
    {
        nod = Q.front();
        Q.pop();
        ap[nod]++;
        if(ap[nod] > m)
        {
            g << "Ciclu negativ!";
            return 0;
        }
        for(auto it:G[nod])
        {
            if(dist[nod] + it.second < dist[it.first])
            {
                dist[it.first] = dist[nod] + it.second;
                Q.push(it.first);
            }
        }
    }
    for(int i = 2; i <= n; i++)
        g << dist[i] << " ";
    return 0;
}