Cod sursa(job #2076685)

Utilizator stefii_predaStefania Preda stefii_preda Data 26 noiembrie 2017 22:17:11
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.41 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");

const int N =  50005;
const int INF = 1000000000;

struct pereche
{
    int nod, cost;
};
vector <pereche> g[N];
queue <int> q;

int cnt[N], d[N];
bool incoada[N];

int main()
{
    int n, m, i, x, y, c;
    in >> n >> m;
    for(i = 1; i <= m; i++)
    {
        in >> x >> y >> c;
        g[x].push_back({y, c});
    }
    for (i = 1; i <= n; i++)
    {
        d[i] = INF;
    }
    d[1] = 0;
    incoada[1] = true;
    cnt[1] = 1;
    q.push(1);
    int vf;
    while (!q.empty())
    {
        vf = q.front();
        q.pop();
        incoada[vf] = false;
        for(i = 0; i < g[vf].size(); ++i)
        {
            if(d[g[vf][i].nod] > d[vf] + g[vf][i].cost)
            {
                d[g[vf][i].nod] = d[vf] + g[vf][i].cost;
                if(incoada[g[vf][i].nod] == false)
                    {
                        q.push(g[vf][i].nod);
                        incoada[g[vf][i].nod] = true;
                    }
                cnt[g[vf][i].nod]++;
                if(cnt[g[vf][i].nod] == n)
                {
                    out << "Ciclu negativ!";
                    return 0;
                }

            }

        }
    }
    for(i = 2; i <= n; i++)
        out << d[i] << " ";
    return 0;
}