Cod sursa(job #1786731)

Utilizator NicuBaciuNicu Baciu NicuBaciu Data 23 octombrie 2016 15:45:34
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

struct muchie
{
    int y;
    int c;
};

struct nod
{
    vector <muchie> v;
    int nrp=0;
    int dist=250000010;
};

nod g[50001];

int n, m;

queue <int> q;

int main()
{
    fin >> n >> m;

    for(int i=1; i<=m; i++)
    {
        int x, y, c;
        muchie m0;

        fin >> x >> y >> c;

        m0.y=y;
        m0.c=c;

        g[x].v.push_back(m0);
    }

    g[1].dist=0;
    q.push(1);

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

        g[ct].nrp++;
        if(g[ct].nrp>m)
        {
            fout << "Ciclu negativ!";
            return 0;
        }

        for(int i=0; i<g[ct].v.size(); i++)
        {
            if(g[ct].dist+g[ct].v[i].c < g[g[ct].v[i].y].dist)
            {
                g[g[ct].v[i].y].dist = g[ct].dist+g[ct].v[i].c;
                q.push(g[ct].v[i].y);
            }
        }
    }

    for(int i=2; i<=n; i++)
    {
        fout << g[i].dist << " ";
    }

    return 0;
}