Cod sursa(job #1747141)

Utilizator SaitamaSaitama-san Saitama Data 24 august 2016 16:00:28
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include <bits/stdc++.h>
#define Nmax 50005
#define INF 1000000000

using namespace std;

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

struct muchie
{
    int nod, cost;
};
vector <muchie> L[Nmax];
bool viz[Nmax], Negativ;
int d[Nmax], cnt[Nmax];
queue <int> q;
int n, m;


void BellmanFord()
{
    int j, c, i, nod, len;
    while(!q.empty() && !Negativ)
    {
        nod = q.front();
        q.pop();
        viz[nod] = false;
        len = L[nod].size();
        for(i = 0; i < len; ++i)
        {
            j = L[nod][i].nod;
            c = L[nod][i].cost;
            if(d[j] > d[nod] + c)
            {
                d[j] = d[nod] + c;
                if(!viz[j])
                {
                    q.push(j);
                    viz[j] = true;
                    cnt[j]++;
                    if(cnt[j] > n)
                        Negativ = true;
                }
            }
        }
    }
}

int main()
{
    int i, nod;
    muchie w;
    fin >> n >> m;
    for(i = 1; i <= m; i++)
    {
        fin >> nod >> w.nod >> w.cost;
        L[nod].push_back(w);
    }
    for(i = 1;i <= n; i++)
        d[i] = INF;
    d[1] = 0;
    viz[1] = true;
    cnt[1] = 1;
    q.push(1);
    BellmanFord();
    if(Negativ)
        fout << "Ciclu negativ!";
    else
    {
        for(i = 2; i <= n; ++i)
            fout << d[i] << " ";
        fout << "\n" ;
    }
    return 0;
}