Cod sursa(job #1506519)

Utilizator cristian.caldareaCaldarea Cristian Daniel cristian.caldarea Data 20 octombrie 2015 19:11:56
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

const int Dim = 50003, Inf = 0x3f3f3f3f;

vector<vector<pair<int,int>>> G;
queue<int> q;
vector<bool> inQ;
int d[Dim], nr[Dim];

int n, m;

void Read();
void Bellmanford();

int main()
{
    Read();
    Bellmanford();
    return 0;
}
void Read()
{
    fin >> n >> m;
    int x, y, z;
    G = vector<vector<pair<int, int>>>(n+1, vector<pair<int, int>>());
    inQ = vector<bool>(n+1);
    for ( int i = 1; i <= m; i++ )
    {
        fin >> x >> y >> z;
        G[x].push_back({y, z});
    }
}
void Bellmanford()
{
    q.push(1);
    inQ[1] = 1;
    d[1] = 0;
    for (int i = 2; i <=n; i++)
        d[i] = Inf;
    int x, y;
    while ( !q.empty() )
    {
        x = q.front();
        q.pop();
        inQ[x] = 0;

        for (auto w : G[x] )
        {
            y = w.first;
            if (d[y] > d[x] + w.second)
            {
                d[y] = d[x] + w.second;
                if (!inQ[y])
                {
                    nr[y]++;
                    if (nr[y] == n)
                    {
                        fout << "Ciclu negativ!";
                        return ;
                    }
                    q.push(y);
                    inQ[y] = 1;
                }
            }
        }
    }

    for (int i = 2; i <= n; i++)
        fout << d[i] << " ";
}