Cod sursa(job #2373064)

Utilizator alexandra_paticaAndreea Alexandra Patica alexandra_patica Data 7 martie 2019 12:03:34
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
ifstream f ("bellmanford.in");
ofstream g ("bellmanford.out");

int n, i, m, x, y, c, d[100002], ciclu[100002];
vector<int>G[100002], C[100002];
queue<int>q;


int bellmanford(int x)
{
    memset(d, 1, sizeof(d));

    d[x]=0;
    q.push(x);

    while (!q.empty())
    {
        x=q.front();
        q.pop();

        ciclu[x]++;
        if (ciclu[x]>n)
            return -1;

        for (int i=0; i<G[x].size(); i++)
        {
            if (d[G[x][i]] > d[x]+C[x][i])
            {
                d[G[x][i]] = d[x]+C[x][i];
                q.push(G[x][i]);
            }
        }
    }
    return 1;
}

int main ()
{
    f >> n >> m;
    for (int i=1; i<=m; i++)
    {
        f >> x >> y >> c;
        G[x].push_back(y);
        C[x].push_back(c);
    }

    c = bellmanford(1);

    if (c>0)
    {
        for (int i=2; i<=n; i++)
            g << d[i] << " ";
    }
    else g << "Ciclu negativ";
    return 0;
}